#!/bin/bash
set -e

ENVIRONMENT=$1

if [ -z "$ENVIRONMENT" ]; then
  echo "Usage: $0 <staging|production>"
  exit 1
fi

# Define cleanup function to revert changes to applications.yaml
cleanup() {
  if [ -f k8s/argocd/base/applications.yaml.bak ]; then
    echo "Reverting k8s/argocd/base/applications.yaml..."
    mv k8s/argocd/base/applications.yaml.bak k8s/argocd/base/applications.yaml
  fi
}
trap cleanup EXIT

if [ "$ENVIRONMENT" == "staging" ]; then
  echo "Deploying to STAGING..."
  
  # Source activation script
  if [ -f ~/bin/activate-stg ]; then
    source ~/bin/activate-stg
  else
    echo "Error: ~/bin/activate-stg not found."
    exit 1
  fi

  # Set BITBUCKET_BRANCH
  export BITBUCKET_BRANCH=$(git rev-parse --abbrev-ref HEAD)
  if [ -z "$BITBUCKET_BRANCH" ]; then
    export BITBUCKET_BRANCH="develop"
  fi
  echo "Using branch: $BITBUCKET_BRANCH"

  # Template argocd/base/applications.yaml
  # Template argocd/base/applications.yaml
  echo "Templating k8s/argocd/base/applications.yaml..."
  
  # Backup original file
  cp k8s/argocd/base/applications.yaml k8s/argocd/base/applications.yaml.bak
  
  # Perform substitution
  envsubst < k8s/argocd/base/applications.yaml.bak > k8s/argocd/base/applications.yaml

  # Apply Kustomize
  echo "Applying Kustomize for staging..."
  kubectl -n argocd apply -k k8s/argocd/overlays/staging --server-side --force-conflicts

  # Rollout restarts
  echo "Restarting coturn deployments..."
  kubectl -n coturn rollout restart deployment/coturn
  kubectl -n coturn rollout status -w deployment/coturn
  kubectl -n coturn-dns rollout restart deployment/coturn-dns
  kubectl -n coturn-dns rollout status -w deployment/coturn-dns

elif [ "$ENVIRONMENT" == "production" ]; then
  echo "Deploying to PRODUCTION..."

  # Source activation script
  if [ -f ~/bin/activate-prd ]; then
    source ~/bin/activate-prd
  else
    echo "Error: ~/bin/activate-prd not found."
    exit 1
  fi

  # Apply Kustomize
  echo "Applying Kustomize for production..."
  kubectl -n argocd apply -k k8s/argocd/overlays/production --server-side --force-conflicts

  # Rollout restarts
  echo "Restarting coturn deployments..."
  kubectl -n coturn rollout restart deployment/coturn
  kubectl -n coturn rollout status -w deployment/coturn
  kubectl -n coturn-dns rollout restart deployment/coturn-dns
  kubectl -n coturn-dns rollout status -w deployment/coturn-dns

else
  echo "Invalid environment: $ENVIRONMENT. Must be 'staging' or 'production'."
  exit 1
fi

echo "Deployment complete!"
