#!/bin/bash
set -e

# Retry helm s3 push with backoff
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
}

echo "=== Starting deployment of tbi-rlv-mobile-api-proxy ==="

# Configuration
SERVICE="tbi-rlv-mobile-api-proxy"
NAMESPACE="redtag"
ENVIRONMENT="${DEPLOY_ENV:-dev}"
CHART_VERSION="1.0.0"
HELM_S3_BUCKET="${HELM_S3_BUCKET:-tbi-charts}"

# Validate
if [ -z "${CLUSTER_NAME}" ]; then
    echo "ERROR: CLUSTER_NAME not set (e.g., 'dev', 'redtag-prod')"
    exit 1
fi

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

# Determine chart path
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CHART_PATH="${SCRIPT_DIR}/../charts/${SERVICE}"

echo ""
echo "=== Step 1: Package Helm chart ==="
sed -i.bak "s|version:.*|version: ${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 "✓ Chart packaged"

echo ""
echo "=== Step 2: Push chart to S3 ==="
helm repo add tbi-charts s3://${HELM_S3_BUCKET}/ || true
helm_s3_push_with_retry "/tmp/helm-charts/${SERVICE}-${CHART_VERSION}.tgz" tbi-charts
echo "✓ Chart pushed to S3"

echo ""
echo "=== Step 3: Deploy to Kubernetes ==="
helm repo update

# Deploy — no secrets file needed for this service (pure proxy, no env vars)
helm upgrade --install \
    --namespace ${NAMESPACE} ${SERVICE} \
    tbi-charts/${SERVICE} \
    --set cluster="${CLUSTER_NAME}" \
    --version ${CHART_VERSION} \
    --kube-context ${CLUSTER_NAME} \
    --reset-values

echo ""
echo "=== Step 4: Verify deployment ==="
kubectl --context ${CLUSTER_NAME} -n ${NAMESPACE} rollout status deployment/${SERVICE} --timeout=3m

echo ""
echo "=== Deployment Complete ==="
kubectl --context ${CLUSTER_NAME} -n ${NAMESPACE} get pods -l app=${SERVICE}
