#!/bin/bash

# Variables
SUBSCRIPTION_ID="213596c9-34b2-4677-a712-45ed127cdae5"
RESOURCE_GROUP="volucy-group"
APP_NAME="poweron-gateway"
DOMAIN_NAME="gateway.poweron-center.net"
CERT_PASSWORD="TheSecurePass$(date +%s)"  # Unique password with timestamp

# Login to Azure (uncomment if not already logged in)
# az login

# Set subscription
echo "Setting subscription..."
az account set --subscription "$SUBSCRIPTION_ID"

# Create directory for certificate files
mkdir -p cert-files
cd cert-files

# Create OpenSSL config file with required extensions
cat > openssl.cnf << EOF
[ req ]
default_bits       = 2048
distinguished_name = req_distinguished_name
req_extensions     = req_ext
[ req_distinguished_name ]
countryName                = Country Name (2 letter code)
stateOrProvinceName        = State or Province Name (full name)
localityName               = Locality Name (eg, city)
organizationName           = Organization Name (eg, company)
commonName                 = Common Name (e.g. server FQDN)
[ req_ext ]
subjectAltName = @alt_names
extendedKeyUsage = serverAuth
[alt_names]
DNS.1   = ${DOMAIN_NAME}
EOF

# Generate private key
openssl genrsa -out private.key 2048

# Create CSR with config file
openssl req -new -key private.key -out request.csr -config openssl.cnf -subj "/C=US/ST=State/L=City/O=Organization/CN=${DOMAIN_NAME}"

# Generate self-signed certificate with extensions
openssl x509 -req -days 365 -in request.csr -signkey private.key -out certificate.crt \
  -extfile openssl.cnf -extensions req_ext

# Create PFX file
openssl pkcs12 -export -out self-signed-cert.pfx -inkey private.key -in certificate.crt -passout pass:$CERT_PASSWORD

cd ..

# Upload certificate to App Service
echo "Uploading certificate..."
UPLOAD_RESULT=$(az webapp config ssl upload \
  --resource-group "$RESOURCE_GROUP" \
  --name "$APP_NAME" \
  --certificate-file "cert-files/self-signed-cert.pfx" \
  --certificate-password "$CERT_PASSWORD")

# Extract thumbprint from upload result
CERT_THUMBPRINT=$(echo $UPLOAD_RESULT | jq -r '.thumbprint')

echo "Certificate uploaded successfully with thumbprint: $CERT_THUMBPRINT"

# If the thumbprint is empty, try to find it another way
if [ -z "$CERT_THUMBPRINT" ] || [ "$CERT_THUMBPRINT" == "null" ]; then
  echo "Thumbprint not found in upload result. Trying to list certificates..."
  CERT_LIST=$(az webapp config ssl list --resource-group "$RESOURCE_GROUP")
  
  # Look for the most recently uploaded certificate
  CERT_THUMBPRINT=$(echo $CERT_LIST | jq -r 'sort_by(.expirationDate) | reverse | .[0].thumbprint')
  
  if [ -z "$CERT_THUMBPRINT" ] || [ "$CERT_THUMBPRINT" == "null" ]; then
    echo "Error: Could not find certificate thumbprint."
    exit 1
  fi
fi

echo "Using certificate thumbprint: $CERT_THUMBPRINT"

# Make sure the custom domain is added
echo "Checking if custom domain exists..."
DOMAIN_EXISTS=$(az webapp config hostname list --resource-group "$RESOURCE_GROUP" --webapp-name "$APP_NAME" | jq -r ".[] | select(.name==\"$DOMAIN_NAME\") | .name")

if [ -z "$DOMAIN_EXISTS" ]; then
  echo "Adding custom domain..."
  az webapp config hostname add \
    --resource-group "$RESOURCE_GROUP" \
    --webapp-name "$APP_NAME" \
    --hostname "$DOMAIN_NAME"
fi

# Add IP-based SSL binding
echo "Creating IP-based SSL binding..."
az webapp config ssl bind \
  --resource-group "$RESOURCE_GROUP" \
  --name "$APP_NAME" \
  --certificate-thumbprint "$CERT_THUMBPRINT" \
  --ssl-type "IP"

echo "SSL binding completed. Your domain should now be secured."