#!/bin/bash
set -e

# Retry helm s3 push with backoff to handle S3 PreconditionFailed 412 race conditions
helm_s3_push_with_retry() {
    local chart_file="$1"
    local repo_name="$2"
    local max_retries=5
    local attempt=1
    local wait_time=5
    while [ $attempt -le $max_retries ]; do
        if helm s3 push "${chart_file}" "${repo_name}" --force 2>&1; then
            return 0
        fi
        echo "helm s3 push failed (attempt ${attempt}/${max_retries}), retrying in ${wait_time}s..."
        sleep $wait_time
        wait_time=$((wait_time * 2))
        attempt=$((attempt + 1))
    done
    echo "ERROR: helm s3 push failed after ${max_retries} attempts"
    return 1
}

# Retry git push with rebase to handle concurrent pipeline race conditions
git_push_with_retry() {
    local branch="${1:-master}"
    local max_retries=5
    local attempt=1
    while [ $attempt -le $max_retries ]; do
        if git push origin "$branch" 2>&1; then
            return 0
        fi
        echo "Push failed (attempt ${attempt}/${max_retries}), rebasing and retrying..."
        git pull --rebase origin "$branch"
        attempt=$((attempt + 1))
    done
    echo "ERROR: Failed to push after ${max_retries} attempts"
    return 1
}
echo "=== Starting deployment of ACC Hotel Mapping Service ==="

# Configuration
SERVICE_NAME="tbi-acc-hotel-mapping-service"
NAMESPACE="redtag"
# Derive environment from branch name if DEPLOY_ENV not explicitly set
case ${CIRCLE_BRANCH} in
  develop) DEFAULT_ENV="dev" ;;
  qa) DEFAULT_ENV="qa" ;;
  uat) DEFAULT_ENV="uat" ;;
  master|main) DEFAULT_ENV="prod" ;;
  *) DEFAULT_ENV="dev" ;;
esac
ENVIRONMENT="${DEPLOY_ENV:-${DEFAULT_ENV}}"
AWS_REGION="${AWS_REGION:-ca-central-1}"
TBI_ENVIRONMENTS_BRANCH="${TBI_ENVIRONMENTS_BRANCH:-master}"
HELM_REPO_URL="${HELM_REPO_URL:-https://tbi-charts.s3.amazonaws.com}"
HELM_S3_BUCKET="${HELM_S3_BUCKET:-tbi-charts}"

# Validate required environment variables
# Default CLUSTER_NAME to ENVIRONMENT if not explicitly set
CLUSTER_NAME="${CLUSTER_NAME:-${ENVIRONMENT}}"

if [ -z "${CLUSTER_NAME}" ]; then
    echo "ERROR: CLUSTER_NAME environment variable is not set!"
    echo "This should be set in CircleCI context (e.g., 'dev', 'qa', 'uat', etc.)"
    exit 1
fi

if [ -z "${AWS_ACCOUNT_ID}" ]; then
    echo "ERROR: AWS_ACCOUNT_ID environment variable is not set!"
    echo "This is required to construct ECR image URLs"
    exit 1
fi

if [ -z "${GITHUB_TOKEN}" ]; then
    echo "ERROR: GITHUB_TOKEN environment variable is not set!"
    echo "This token is required to clone and push to tbi-environments repository"
    exit 1
fi

# Clean URL - no inline token (credential helper supplies it at request time)
TBI_ENVIRONMENTS_REPO="https://github.com/redlabelvacations/tbi-environments.git"

# Read image tag from workspace (created by build job)
if [ -f "IMAGE_TAG" ]; then
    CHART_VERSION=$(cat IMAGE_TAG | tr -d '[:space:]')
    echo "Using image tag from build job: ${CHART_VERSION}"
else
    echo "WARNING: IMAGE_TAG file not found, calculating from VERSION file"
    if [ ! -f "VERSION" ]; then
        echo "ERROR: VERSION file not found!"
        exit 1
    fi
    BASE_VERSION=$(cat VERSION | tr -d '[:space:]')
    CHART_VERSION="${BASE_VERSION}-${CIRCLE_BRANCH}-${CIRCLE_BUILD_NUM}"
fi

echo "Chart Version: ${CHART_VERSION}"
echo "Environment: ${ENVIRONMENT}"
echo "Namespace: ${NAMESPACE}"
echo "Cluster: ${CLUSTER_NAME}"
echo "Service: ${SERVICE_NAME}"

# Function to package Helm chart
package_helm_chart() {
    echo ""
    echo "=== Packaging Helm chart for ${SERVICE_NAME} ==="

    local chart_path="tbi-devops-environments/${ENVIRONMENT}/${SERVICE_NAME}/charts/${SERVICE_NAME}"

    if [ ! -d "${chart_path}" ]; then
        echo "ERROR: Chart directory not found: ${chart_path}"
        return 1
    fi

    # Update Chart.yaml with new version
    echo "Updating chart version to ${CHART_VERSION}..."
    sed -i.bak "s|version:.*|version: ${CHART_VERSION}|g" ${chart_path}/Chart.yaml
    sed -i.bak "s|appVersion:.*|appVersion: \"${CHART_VERSION}\"|g" ${chart_path}/Chart.yaml
    rm -f ${chart_path}/Chart.yaml.bak

    # Package the chart
    echo "Packaging chart..."
    mkdir -p /tmp/helm-charts
    helm package ${chart_path} -d /tmp/helm-charts

    echo "✓ ${SERVICE_NAME} chart packaged"
}

# Function to push chart to S3 Helm repository
push_chart_to_s3_repo() {
    local chart_file="/tmp/helm-charts/${SERVICE_NAME}-${CHART_VERSION}.tgz"

    echo ""
    echo "=== Pushing ${SERVICE_NAME} chart to S3 Helm repository ==="

    if [ ! -f "${chart_file}" ]; then
        echo "ERROR: Chart file not found: ${chart_file}"
        return 1
    fi

    # Use helm-s3 plugin to push chart (automatically updates index.yaml)
    helm_s3_push_with_retry ${chart_file} tbi-charts

    echo "✓ ${SERVICE_NAME} chart pushed to S3 repository"
}

# Function to clone tbi-environments repo
clone_tbi_environments() {
    echo ""
    echo "=== Cloning tbi-environments repository ==="

    if [ -d "/tmp/tbi-environments" ]; then
        rm -rf /tmp/tbi-environments
    fi

    git -c credential.helper= \
        -c credential.helper='!f() { echo "username=x-access-token"; echo "password=${GITHUB_TOKEN}"; }; f' \
        clone "${TBI_ENVIRONMENTS_REPO}" /tmp/tbi-environments
    # Persist the helper so the later git push also authenticates
    git -C /tmp/tbi-environments config credential.helper '!f() { echo "username=x-access-token"; echo "password=${GITHUB_TOKEN}"; }; f'
    cd /tmp/tbi-environments
    git checkout ${TBI_ENVIRONMENTS_BRANCH}

    echo "✓ tbi-environments cloned successfully"
}

# Function to update requirements.yaml
update_requirements() {
    echo ""
    echo "=== Updating requirements.yaml for ${SERVICE_NAME} ==="

    local req_file="/tmp/tbi-environments/${ENVIRONMENT}/requirements.yaml"

    if [ ! -f "${req_file}" ]; then
        echo "ERROR: Requirements file not found: ${req_file}"
        return 1
    fi

    # Update version using sed
    sed -i.bak "/name: ${SERVICE_NAME}/,/version:/ s|version:.*|version: ${CHART_VERSION}|" ${req_file}
    rm -f ${req_file}.bak

    echo "✓ Updated ${SERVICE_NAME} to version ${CHART_VERSION} in requirements.yaml"
}

# Function to update image in values file
update_values_file() {
    echo ""
    echo "=== Updating values file for ${SERVICE_NAME} ==="

    local values_file="/tmp/tbi-environments/${ENVIRONMENT}/values/${SERVICE_NAME}.yaml"

    if [ ! -f "${values_file}" ]; then
        echo "ERROR: Values file not found: ${values_file}"
        return 1
    fi

    # Construct ECR image URL
    local image_url="${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/${SERVICE_NAME}:${CHART_VERSION}"

    echo "Image URL: ${image_url}"

    # Check if image field exists in the file
    if grep -q "^image:" "${values_file}"; then
        # Update existing image field
        sed -i.bak "s|^image:.*|image: ${image_url}|" ${values_file}
        echo "Updated existing image field"
    else
        # Add image field at the top of the file
        sed -i.bak "1 a\\
image: ${image_url}" ${values_file}
        echo "Added new image field"
    fi
    rm -f ${values_file}.bak

    echo "✓ Updated ${SERVICE_NAME} image to ${image_url}"
}

# Function to commit and push values file updates
push_values_update() {
    echo ""
    echo "=== Pushing values file updates ==="

    cd /tmp/tbi-environments

    # Configure git
    git config user.name "CircleCI Bot"
    git config user.email "circleci@tbidevelopment.ca"

    # Show changes
    echo "Changes made:"
    git diff ${ENVIRONMENT}/values/
    git diff ${ENVIRONMENT}/requirements.yaml

    # Stage files for commit
    git add ${ENVIRONMENT}/values/${SERVICE_NAME}.yaml
    git add ${ENVIRONMENT}/requirements.yaml

    # ✅ CHECK IF THERE ARE ANY CHANGES BEFORE COMMITTING
    if git diff --cached --quiet; then
        echo "ℹ️  No changes detected - values already up to date with version ${CHART_VERSION}"
        echo "Skipping commit and continuing with deployment..."
    else
        # Commit and push values file AND requirements.yaml
        git commit -m "Update ${SERVICE_NAME} to ${CHART_VERSION}

Deployed by CircleCI build #${CIRCLE_BUILD_NUM}
Branch: ${CIRCLE_BRANCH}
Service: ${SERVICE_NAME}

Changes:
- Updated values file with ECR image URL: ${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/${SERVICE_NAME}:${CHART_VERSION}
- Updated requirements.yaml with chart version: ${CHART_VERSION}
"
        git_push_with_retry "${TBI_ENVIRONMENTS_BRANCH}"
        echo "✅ Values file and requirements.yaml updated and pushed"
    fi
}

# Function to deploy service using helm secrets
deploy_service() {
    echo ""
    echo "=== Deploying ${SERVICE_NAME} using helm secrets ==="

    cd /tmp/tbi-environments

    # Display expected image
    local image_url="${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/${SERVICE_NAME}:${CHART_VERSION}"
    echo "Expected image (from values file): ${image_url}"

    # Deploy using helm secrets
    echo "Running: helm secrets upgrade --install --namespace ${NAMESPACE} ${SERVICE_NAME} --set cluster=${CLUSTER_NAME} --version ${CHART_VERSION}"
    helm secrets upgrade --install \
        --namespace ${NAMESPACE} ${SERVICE_NAME} \
        tbi-charts/${SERVICE_NAME} \
        --set cluster="${CLUSTER_NAME}" \
        --version ${CHART_VERSION} \
        --reset-values \
        -f ./${ENVIRONMENT}/common.yaml \
        -f ./${ENVIRONMENT}/secrets.common.yaml \
        -f ./${ENVIRONMENT}/values/${SERVICE_NAME}.yaml \
        -f ./${ENVIRONMENT}/secrets/secrets.${SERVICE_NAME}.yaml

    # Verify deployment
    echo "Verifying deployment..."
    kubectl rollout status deployment/${SERVICE_NAME} -n ${NAMESPACE} --timeout=5m

    echo "✅ ${SERVICE_NAME} deployed successfully"
}

# Main deployment flow
echo ""
echo "=== Step 1: Package Helm chart ==="
package_helm_chart

echo ""
echo "=== Step 2: Initialize Helm S3 repository ==="
helm repo add tbi-charts s3://${HELM_S3_BUCKET}/

echo ""
echo "=== Step 3: Push chart to S3 repository ==="
push_chart_to_s3_repo

echo ""
echo "=== Step 4: Clone tbi-environments repository ==="
clone_tbi_environments

echo ""
echo "=== Step 5: Update values file with image URL ==="
update_values_file

echo ""
echo "=== Step 6: Update requirements.yaml ==="
update_requirements

echo ""
echo "=== Step 7: Commit and push values file update ==="
push_values_update

echo ""
echo "=== Step 8: Update Helm repository ==="
helm repo update

echo ""
echo "=== Step 9: Deploy service to Kubernetes ==="
deploy_service

echo ""
echo "=== Deployment Summary ==="
kubectl get deployment ${SERVICE_NAME} -n ${NAMESPACE}
kubectl get pods -n ${NAMESPACE} -l app=${SERVICE_NAME}

echo ""
echo "=== Deployment Complete ==="
echo "Service deployed to version: ${CHART_VERSION}"
