#!/bin/bash

# Check if input file is provided first
if [ "$#" -ne 1 ]; then
    echo "Usage: $0 <subscription_list_file.csv>"
    exit 1
fi

# Set input file variable
input_file=$1

# Set explicit log file location
LOG_DIR="./logs"
mkdir -p "$LOG_DIR"
log_file="$LOG_DIR/function_app_update_$(date +%Y%m%d_%H%M%S).log"

# Define the new package URLs
FUNCTION_PACKAGE_URL="https://cs-csgov-laggar-cloudconnect-templates.s3-us-gov-west-1.amazonaws.com/azure/3.11/ioa.zip"

# Add initial logging
echo "Script started at $(date)" > "$log_file"
echo "Using input file: $input_file" >> "$log_file"
echo "AAD Package URL: $FUNCTION_PACKAGE_URL" >> "$log_file"
echo "Activity Package URL: $FUNCTION_PACKAGE_URL" >> "$log_file"

# Check if file exists
if [ ! -f "$input_file" ]; then
    echo "Error: File $input_file not found!" | tee -a "$log_file"
    exit 1
fi

# Clean the input file in place
echo "Cleaning input file..." | tee -a "$log_file"
# Create a temporary file
temp_file=$(mktemp)

# Clean the file: remove carriage returns, extra spaces, and trailing characters
# Preserve only valid lines while maintaining the header
{
    # Read the header
    read -r header
    echo "$header"
    # Process remaining lines
    while IFS= read -r line || [ -n "$line" ]; do
        # Clean the line and output only if it contains a valid subscription ID pattern
        echo "$line" | tr -d '\r' | tr -d '%' | sed 's/[[:space:]]*$//' | grep -E '^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$' || true
    done
} < "$input_file" > "$temp_file"

# Replace original file with cleaned version
mv "$temp_file" "$input_file"

echo "File cleaned successfully" | tee -a "$log_file"

# Check Azure CLI login status
echo "Checking Azure CLI login status..." | tee -a "$log_file"
az account show >> "$log_file" 2>&1
if [ $? -ne 0 ]; then
    echo "Error: Not logged into Azure CLI. Please run 'az login' first" | tee -a "$log_file"
    exit 1
fi

# Display file contents
echo "Content of input file:" | tee -a "$log_file"
cat "$input_file" | tee -a "$log_file"

# Function to update and restart app
update_and_restart() {
    local sub_id=$1
    local app_name=$2
    local package_url=$3

    echo "Processing $app_name in subscription $sub_id..." | tee -a "$log_file"

    # Get resource group name
    rg_name=$(az functionapp list --subscription "$sub_id" --query "[?name=='$app_name'].resourceGroup" -o tsv)

    if [ -z "$rg_name" ]; then
        echo "Error: Could not find resource group for $app_name in subscription $sub_id" | tee -a "$log_file"
        return 1
    fi

    echo "Found resource group: $rg_name for $app_name" | tee -a "$log_file"

    # Update Python version
    echo "Updating Python version for $app_name..." | tee -a "$log_file"
    az functionapp config set \
        --subscription "$sub_id" \
        --name "$app_name" \
        --resource-group "$rg_name" \
        --linux-fx-version "PYTHON|3.11" \
        2>> "$log_file"

    if [ $? -ne 0 ]; then
        echo "Error: Failed to update Python version for $app_name" | tee -a "$log_file"
        return 1
    fi

    # Update app settings (WEBSITE_RUN_FROM_PACKAGE and FUNCTIONS_WORKER_RUNTIME_VERSION)
    echo "Updating app settings for $app_name..." | tee -a "$log_file"
    echo "Setting WEBSITE_RUN_FROM_PACKAGE to: $package_url" | tee -a "$log_file"
    echo "Setting FUNCTIONS_WORKER_RUNTIME_VERSION to: 3.11" | tee -a "$log_file"

    az functionapp config appsettings set \
        --subscription "$sub_id" \
        --name "$app_name" \
        --resource-group "$rg_name" \
        --settings "WEBSITE_RUN_FROM_PACKAGE=$package_url" "FUNCTIONS_WORKER_RUNTIME_VERSION=3.11" \
        2>> "$log_file"

    if [ $? -ne 0 ]; then
        echo "Error: Failed to update app settings for $app_name" | tee -a "$log_file"
        return 1
    fi

    # Restart function app
    echo "Restarting $app_name..." | tee -a "$log_file"
    az functionapp restart \
        --subscription "$sub_id" \
        --name "$app_name" \
        --resource-group "$rg_name" \
        2>> "$log_file"

    if [ $? -ne 0 ]; then
        echo "Error: Failed to restart $app_name" | tee -a "$log_file"
        return 1
    fi

    echo "Successfully updated and restarted $app_name" | tee -a "$log_file"
    return 0
}

# Process each subscription from CSV
tail -n +2 "$input_file" | while IFS= read -r sub_id; do
    # Debug logging
    echo "Read line: '$sub_id'" | tee -a "$log_file"

    # Clean the subscription ID (remove quotes and whitespace)
    sub_id=$(echo "$sub_id" | tr -d '"' | tr -d ' ')
    echo "Cleaned subscription ID: '$sub_id'" | tee -a "$log_file"

    # Skip empty lines and comments
    if [[ -z "$sub_id" || "$sub_id" =~ ^[[:space:]]*# ]]; then
        echo "Skipping empty line or comment" | tee -a "$log_file"
        continue
    fi

    echo "Processing subscription: $sub_id" | tee -a "$log_file"

    # Process AAD function app
    aad_app="cs-aad-func-${sub_id}"
    echo "Attempting to update AAD app: $aad_app" | tee -a "$log_file"
    update_and_restart "$sub_id" "$aad_app" "$FUNCTION_PACKAGE_URL"

    # Process Activity function app
    activity_app="cs-activity-func-${sub_id}"
    echo "Attempting to update Activity app: $activity_app" | tee -a "$log_file"
    update_and_restart "$sub_id" "$activity_app" "$FUNCTION_PACKAGE_URL"

    echo "Completed processing subscription: $sub_id" | tee -a "$log_file"
    echo "----------------------------------------" | tee -a "$log_file"
done

echo "Script execution completed. Check $log_file for details."