#!/bin/bash
set -e

# Deployment script for tbi-hlx-whitelabel-frontend (uat).
# Values and secrets are sourced from the tbi-environments repo at deploy time.

SERVICE_NAME="tbi-hlx-whitelabel-frontend"
NAMESPACE="helix"
ENVIRONMENT="${DEPLOY_ENV:-uat}"
AWS_REGION="${AWS_REGION:-ca-central-1}"
TBI_ENVIRONMENTS_BRANCH="${TBI_ENVIRONMENTS_BRANCH:-master}"
HELM_S3_BUCKET="${HELM_S3_BUCKET:-tbi-charts}"

helm_s3_push_with_retry() {
    local chart_file="$1"; local repo_name="$2"
    local max_retries=5 attempt=1 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 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
}

for v in CLUSTER_NAME AWS_ACCOUNT_ID GITHUB_TOKEN; do
    if [ -z "${!v:-}" ]; then echo "ERROR: ${v} is not set!"; exit 1; fi
done

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

if [ -f "IMAGE_TAG" ]; then
    CHART_VERSION=$(cat IMAGE_TAG | tr -d '[:space:]')
else
    BASE_VERSION=$(cat VERSION 2>/dev/null | tr -d '[:space:]' || echo "1.0.0")
    CHART_VERSION="${BASE_VERSION}-${CIRCLE_BRANCH}-${CIRCLE_BUILD_NUM}"
fi

echo "Service: ${SERVICE_NAME} | Env: ${ENVIRONMENT} | Namespace: ${NAMESPACE} | Version: ${CHART_VERSION}"

chart_path="tbi-devops-environments/${ENVIRONMENT}/${SERVICE_NAME}/charts/${SERVICE_NAME}"
[ -d "${chart_path}" ] || { echo "ERROR: chart not found: ${chart_path}"; exit 1; }

echo "=== Packaging Helm chart ==="
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

echo "=== Pushing chart to S3 repo (${HELM_S3_BUCKET}) ==="
helm repo add tbi-charts s3://${HELM_S3_BUCKET}/
helm_s3_push_with_retry "/tmp/helm-charts/${SERVICE_NAME}-${CHART_VERSION}.tgz" tbi-charts

echo "=== Cloning 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}

image_url="${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/${SERVICE_NAME}:${CHART_VERSION}"
values_file="${ENVIRONMENT}/values/${SERVICE_NAME}.yaml"
if [ -f "${values_file}" ]; then
    sed -i.bak "s|^image:.*|image: ${image_url}|g" "${values_file}"; rm -f "${values_file}.bak"
    echo "Updated ${values_file} -> ${image_url}"
else
    echo "WARNING: ${values_file} not found in tbi-environments; create it before deploy."
fi

git config user.name "CircleCI Bot"
git config user.email "circleci@tbidevelopment.ca"
git add "${values_file}" || true
if git diff --cached --quiet; then
    echo "No values changes to commit."
else
    git commit -m "Update ${SERVICE_NAME} image to ${CHART_VERSION} (build #${CIRCLE_BUILD_NUM})"
    git_push_with_retry "${TBI_ENVIRONMENTS_BRANCH}"
fi

echo "=== Deploying with helm secrets ==="
helm repo update
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 "=== Deployment complete: ${CHART_VERSION} ==="
