#!/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 TBI RLV Tours Connector Service ==="

# Configuration
SERVICE_NAME="tbi-rlv-tours-connector-service"
NAMESPACE="rlv"
ENVIRONMENT="uat"
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}"

# Set CLUSTER_NAME based on environment to prevent cross-cluster deployments
case "${ENVIRONMENT}" in
    dev) CLUSTER_NAME="dev" ;;
    qa) CLUSTER_NAME="qa" ;;
    uat) CLUSTER_NAME="uat" ;;
    prod) CLUSTER_NAME="tbi-prod" ;;
    *) echo "ERROR: Unknown environment ${ENVIRONMENT}"; exit 1 ;;
esac

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

if [ -z "${GITHUB_TOKEN}" ]; then
    echo "ERROR: GITHUB_TOKEN environment variable is not set!"
    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 using helm-s3 plugin
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

    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 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

    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

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

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

    cd /tmp/tbi-environments

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

    echo "Changes made:"
    git diff ${ENVIRONMENT}/values/

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

    if git diff --cached --quiet; then
        echo "ℹ️  No changes detected - values already up to date with version ${CHART_VERSION}"
    else
        git commit -m "Update ${SERVICE_NAME} image to ${CHART_VERSION} for ${ENVIRONMENT}

Deployed by CircleCI build #${CIRCLE_BUILD_NUM}
Branch: ${CIRCLE_BRANCH}
Service: ${SERVICE_NAME}
"
        git_push_with_retry "${TBI_ENVIRONMENTS_BRANCH}"
        echo "✓ Values file 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

    # Do NOT call update-kubeconfig again here. setup-kubectl.sh already
    # wrote the UAT context with --role-arn eksAdmin. A second call without
    # that role overwrites kubeconfig and Helm then gets:
    # "Kubernetes cluster unreachable: the server has asked for the client to provide credentials"
    echo "Using existing kubectl context (configured by setup-kubectl.sh with eksAdmin):"
    kubectl config current-context
    unset AWS_PROFILE || true

    # Install the chart we just packaged. Re-downloading tbi-charts/${SERVICE}
    # --version after helm repo update loses the version when a concurrent DEV
    # helm s3 push rewrites index.yaml (0.1.51-uat-1983 was dropped that way).
    local chart_file="/tmp/helm-charts/${SERVICE_NAME}-${CHART_VERSION}.tgz"
    if [ ! -f "${chart_file}" ]; then
        echo "ERROR: Local chart not found: ${chart_file}"
        exit 1
    fi
    echo "Installing from local chart ${chart_file}"
    helm secrets upgrade --install \
        --namespace ${NAMESPACE} ${SERVICE_NAME} \
        "${chart_file}" \
        --set cluster="${CLUSTER_NAME}" \
        --reset-values \
        -f ./${ENVIRONMENT}/common.yaml \
        -f ./${ENVIRONMENT}/secrets.common.yaml \
        -f ./${ENVIRONMENT}/values/${SERVICE_NAME}.yaml \
        -f ./${ENVIRONMENT}/secrets/secrets.${SERVICE_NAME}.yaml

    echo "Verifying deployment..."
    if ! kubectl rollout status deployment/${SERVICE_NAME} -n ${NAMESPACE} --timeout=5m; then
        echo ""
        echo "=== Deployment rollout timed out — dumping cluster diagnostics ==="
        kubectl get deploy,rs,pods,svc,ingress -n ${NAMESPACE} -l app=${SERVICE_NAME} || true
        echo ""
        echo "--- ReplicaSets ---"
        kubectl get rs -n ${NAMESPACE} -l app=${SERVICE_NAME} -o wide || true
        echo ""
        echo "--- Recent events ---"
        kubectl get events -n ${NAMESPACE} --sort-by='.lastTimestamp' | tail -n 50 || true
        echo ""
        echo "--- Deployment describe ---"
        kubectl describe deploy ${SERVICE_NAME} -n ${NAMESPACE} || true
        echo ""
        PODS=$(kubectl get pods -n ${NAMESPACE} -l app=${SERVICE_NAME} -o name 2>/dev/null || true)
        if [ -z "${PODS}" ]; then
            echo "No pods matched label app=${SERVICE_NAME}"
        fi
        for pod in ${PODS}; do
            [ -z "${pod}" ] && continue
            echo ""
            echo "--- Describe ${pod} ---"
            kubectl describe ${pod} -n ${NAMESPACE} || true
            echo ""
            echo "--- Logs ${pod} (current) ---"
            kubectl logs ${pod} -n ${NAMESPACE} --tail=200 || true
            echo ""
            echo "--- Logs ${pod} (previous) ---"
            kubectl logs ${pod} -n ${NAMESPACE} --previous --tail=200 || true
        done
        echo "=== End diagnostics ==="
        exit 1
    fi

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

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


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: Commit and push values file update ==="
push_values_update

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

echo ""
echo "=== Deployment Complete ==="
echo "Service: ${SERVICE_NAME}"
echo "Version: ${CHART_VERSION}"
