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


# Override cluster name - context provides tbi-prod but we deploy to redtag-prod
export CLUSTER_NAME="redtag-prod"

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-sunquest-booking-path ==="

# Configuration
SERVICE_NAME="tbi-sunquest-booking-path"
NAMESPACE="sunquest"
ENVIRONMENT="${DEPLOY_ENV:-redtag-prod}"
AWS_REGION="${AWS_REGION:-ca-central-1}"
TBI_ENVIRONMENTS_BRANCH="${TBI_ENVIRONMENTS_BRANCH:-master}"
HELM_S3_BUCKET="${HELM_S3_BUCKET:-tbi-charts-prod}"

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
package_helm_chart() {
    echo "=== Packaging Helm chart ==="
    local chart_path="tbi-devops-environments/redtag-prod/${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
    # Authenticate via a credential helper (survives GitHub's redirect, unlike an
    # inline token in the URL), and persist it on the clone so the later push works.
    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
    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="${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/tbi-rlv-booking-path:${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
    # Override .sops.yaml to remove aws_profile (not available on runner)
    cat > /tmp/tbi-environments/.sops.yaml << 'SOPSEOF'
creation_rules:
  - kms: arn:aws:kms:ca-central-1:495680544243:key/c3fa2cba-8d35-4448-9993-e17667581699
SOPSEOF

    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

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