#!/usr/bin/env bash
set -euo pipefail

# === KONFIGURASI UTAMA ===
APP_DIR="/home/data/app"
INSTALL_DIR="/home/klbf/installation"
APP_FILES=""           # "https://example.com/a.jar https://example.com/b.jar"
YAML_URL=""            # "https://example.com/08.yaml"
YAML_FILE="08.yaml"    # Nama file YAML yang akan di-download dan di-apply
STOP_AFTER_STEP3=false

RESTART_TARGETS=("healthspeak-api" "klbf-worker")  # nama deployment / label app
USE_DELETE=true    # true/false → pakai kubectl delete pod
USE_ROLLOUT=true   # true/false → pakai kubectl rollout restart (hybrid kalau dua2nya true)

# === FUNGSI RESTART ===
restart_resources() {
  local targets=("$@")

  for name in "${targets[@]}"; do
    echo "=== Restart target: $name ==="

    # 1) Jika USE_ROLLOUT = true → coba rollout restart dulu
    if [ "$USE_ROLLOUT" = "true" ]; then
      echo "[rollout] coba restart deployment/statefulset/daemonset: $name"
      if kubectl get deployment "$name" &>/dev/null; then
        kubectl rollout restart deployment/"$name"
        kubectl rollout status deployment/"$name" --timeout=180s || echo "Warning: rollout status deployment/$name timeout"
      elif kubectl get statefulset "$name" &>/dev/null; then
        kubectl rollout restart statefulset/"$name"
        kubectl rollout status statefulset/"$name" --timeout=180s || echo "Warning: rollout status statefulset/$name timeout"
      elif kubectl get daemonset "$name" &>/dev/null; then
        kubectl rollout restart daemonset/"$name"
        kubectl rollout status daemonset/"$name" --timeout=180s || echo "Warning: rollout status daemonset/$name timeout"
      else
        echo "[rollout] Tidak ditemukan controller bernama $name, skip rollout."
      fi
    fi

    # 2) Jika USE_DELETE = true → delete pod by label app=$name (hybrid jika dua2nya true)
    if [ "$USE_DELETE" = "true" ]; then
      echo "[delete] delete pods dengan label app=$name (jika ada)"
      kubectl delete pod -l app="$name" --grace-period=10 --timeout=60s 2>/dev/null || \
        echo "[delete] Tidak ada pod dengan label app=$name atau delete gagal (lanjut)."
    fi
  done
}

# === CEK ROOT ===
if [ "$EUID" -ne 0 ]; then
  echo "Harus dijalankan sebagai root. Gunakan: sudo $0"
  exit 1
fi

echo "=== Mulai deployment YAML_FILE=$YAML_FILE ==="
echo "Config: APP_DIR=$APP_DIR | INSTALL_DIR=$INSTALL_DIR | STOP_STEP3=$STOP_AFTER_STEP3"

# === STEP 1-3: APP FILES ===
cd "$APP_DIR"
echo "CD ke: $APP_DIR"
if [ -n "$APP_FILES" ]; then
  for url in $APP_FILES; do
    echo "Download: $url"
    wget "$url"
  done
else
  echo "Skip download app files (APP_FILES kosong)"
fi

if [ "$STOP_AFTER_STEP3" = "true" ]; then
  echo "STOP_AFTER_STEP3=true, selesai di step 3."
  exit 0
fi

# === STEP 4-6: YAML + APPLY ===
cd "$INSTALL_DIR"
echo "CD ke: $INSTALL_DIR"

# Hapus YAML_FILE lama (non-blocking)
if [ -f "$YAML_FILE" ]; then
  echo "Hapus $YAML_FILE lama..."
  rm "$YAML_FILE" 2>/dev/null || echo "Warning: gagal hapus $YAML_FILE, lanjut..."
else
  echo "$YAML_FILE tidak ada, skip hapus."
fi

if [ -z "$YAML_URL" ]; then
  echo "Error: YAML_URL kosong, tidak bisa download $YAML_FILE"
  exit 1
fi

echo "Download $YAML_FILE dari: $YAML_URL"
wget -O "$YAML_FILE" "$YAML_URL"

echo "Apply Kubernetes config: $YAML_FILE"
kubectl apply -f "$YAML_FILE"

# === STEP 7: RESTART SESUAI FLAG ===
if [ "${#RESTART_TARGETS[@]}" -gt 0 ] && { [ "$USE_DELETE" = "true" ] || [ "$USE_ROLLOUT" = "true" ]; }; then
  echo "Mulai restart resources (USE_ROLLOUT=$USE_ROLLOUT, USE_DELETE=$USE_DELETE)..."
  restart_resources "${RESTART_TARGETS[@]}"
else
  echo "Skip restart (tidak ada target atau kedua flag false)."
fi

echo "=== Selesai deploy.sh ($YAML_FILE) ==="
