#!/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
}

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 tbi-rlv-vacations-frontend ==="

# Configuration
SERVICE_NAME="tbi-rlv-vacations-frontend"
NAMESPACE="redtag"
ENVIRONMENT="uat"
AWS_REGION="${AWS_REGION:-ca-central-1}"
TBI_ENVIRONMENTS_BRANCH="${TBI_ENVIRONMENTS_BRANCH:-master}"
HELM_S3_BUCKET="${HELM_S3_BUCKET:-tbi-charts}"

# Override cluster name for UAT (actual EKS cluster name)
export CLUSTER_NAME="uat"

if [ -z "${CLUSTER_NAME}" ]; then
    echo "ERROR: CLUSTER_NAME not set!"
    exit 1
fi
if [ -z "${AWS_ACCOUNT_ID}" ]; then
    echo "ERROR: AWS_ACCOUNT_ID not set!"
    exit 1
fi
if [ -z "${GITHUB_TOKEN}" ]; then
    echo "ERROR: GITHUB_TOKEN not set!"
    exit 1
fi

TBI_ENVIRONMENTS_REPO="https://github.com/redlabelvacations/tbi-environments.git"

# Read image tag
if [ -f "IMAGE_TAG" ]; then
    CHART_VERSION=$(cat IMAGE_TAG | tr -d '[:space:]')
else
    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}"

package_helm_chart() {
    echo "=== Packaging Helm chart ==="
    local chart_path="tbi-devops-environments/uat/${SERVICE_NAME}/charts/${SERVICE_NAME}"

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

    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

    mkdir -p /tmp/helm-charts
    helm package ${chart_path} -d /tmp/helm-charts
}

push_chart_to_s3_repo() {
    local chart_file="/tmp/helm-charts/${SERVICE_NAME}-${CHART_VERSION}.tgz"
    if [ ! -f "${chart_file}" ]; then
        echo "ERROR: Chart file not found: ${chart_file}"
        return 1
    fi
    helm_s3_push_with_retry ${chart_file} tbi-charts
}

clone_tbi_environments() {
    rm -rf /tmp/tbi-environments
    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}
}

update_requirements() {
    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
    sed -i.bak "/name: ${SERVICE_NAME}/,/version:/ s|version:.*|version: ${CHART_VERSION}|" ${req_file}
    rm -f ${req_file}.bak
}

update_values_file() {
    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

    local image_url="${ECR_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/${SERVICE_NAME}:${CHART_VERSION}"

    if grep -q "^image:" "${values_file}"; then
        sed -i.bak "s|^image:.*|image: ${image_url}|" ${values_file}
    else
        sed -i.bak "1 a\\
image: ${image_url}" ${values_file}
    fi
    rm -f ${values_file}.bak
}

push_values_update() {
    cd /tmp/tbi-environments
    git config user.name "CircleCI Bot"
    git config user.email "circleci@tbidevelopment.ca"

    git add ${ENVIRONMENT}/values/${SERVICE_NAME}.yaml
    git add ${ENVIRONMENT}/requirements.yaml

    if git diff --cached --quiet; then
        echo "No changes detected - skipping commit"
    else
        git commit -m "Update ${SERVICE_NAME} to ${CHART_VERSION}

Deployed by CircleCI build #${CIRCLE_BUILD_NUM}
Branch: ${CIRCLE_BRANCH}"
        git_push_with_retry "${TBI_ENVIRONMENTS_BRANCH}"
    fi
}

deploy_service() {
    cd /tmp/tbi-environments

    # Ensure tbi-dev AWS profile exists for SOPS decryption
    mkdir -p ~/.aws
    if ! grep -q "\[tbi-dev\]" ~/.aws/credentials 2>/dev/null; then
        cat >> ~/.aws/credentials << EOF
[tbi-dev]
aws_access_key_id=${AWS_ACCESS_KEY_ID}
aws_secret_access_key=${AWS_SECRET_ACCESS_KEY}
EOF
    fi
    if ! grep -q "\[profile tbi-dev\]" ~/.aws/config 2>/dev/null; then
        cat >> ~/.aws/config << EOF
[profile tbi-dev]
region=${AWS_REGION:-ca-central-1}
EOF
    fi

    # Manually decrypt secrets (bypasses helm-secrets plugin issues)
    echo "Decrypting secrets..."
    local secrets_file="./${ENVIRONMENT}/secrets/secrets.${SERVICE_NAME}.yaml"
    local decrypted_file="/tmp/decrypted-secrets-${SERVICE_NAME}.yaml"

    AWS_PROFILE=tbi-dev sops -d "${secrets_file}" > "${decrypted_file}"
    if [ $? -ne 0 ] || [ ! -s "${decrypted_file}" ]; then
        echo "ERROR: Failed to decrypt ${secrets_file}"
        rm -f "${decrypted_file}"
        exit 1
    fi
    echo "✓ Secrets decrypted successfully"

    # Build values file list (skip non-existent or empty files)
    VALUES_ARGS=""
    for f in ./${ENVIRONMENT}/common.yaml ./${ENVIRONMENT}/values/${SERVICE_NAME}.yaml; do
        if [ -f "$f" ] && [ -s "$f" ]; then
            VALUES_ARGS="${VALUES_ARGS} -f $f"
        fi
    done

    # Use decrypted secrets file directly with plain helm (no helm-secrets needed)
    helm upgrade --install \
        --namespace ${NAMESPACE} ${SERVICE_NAME} \
        tbi-charts/${SERVICE_NAME} \
        --set cluster="${CLUSTER_NAME}" \
        --version ${CHART_VERSION} \
        --reset-values \
        ${VALUES_ARGS} \
        -f "${decrypted_file}"

    local helm_exit=$?

    # Clean up decrypted file
    rm -f "${decrypted_file}"

    if [ ${helm_exit} -ne 0 ]; then
        echo "ERROR: Helm upgrade failed!"
        exit 1
    fi

    kubectl rollout status deployment/${SERVICE_NAME} -n ${NAMESPACE} --timeout=5m
    echo "✅ ${SERVICE_NAME} deployed successfully"
}

# Main flow
package_helm_chart
helm repo add tbi-charts s3://${HELM_S3_BUCKET}/

# ECR account: images are built/pushed to dev account ECR, not the deploy account.
ECR_ACCOUNT_ID="${ECR_ACCOUNT_ID:-594765360358}"

push_chart_to_s3_repo
clone_tbi_environments
update_values_file
update_requirements
push_values_update
helm repo update
deploy_service

echo "=== Deployment Complete: ${SERVICE_NAME} v${CHART_VERSION} ==="
