#!/bin/sh
set -eu

REPO="${1:-}"
if [ -z "$REPO" ]; then
  echo "Usage: $0 <repo-name>" >&2
  exit 1
fi

export SOPS_AGE_KEY_FILE="/secrets/age.agekey"
SECRETS_DIR="/repos/SilverSight/infra/secrets"

log() { echo "[$(date -u +%H:%M:%S)] $*"; }

log "Deploy triggered for repo: $REPO"

# Pull latest from git
cd "/repos/SilverSight"
git fetch origin main && git reset --hard origin/main
log "Git updated to $(git rev-parse --short HEAD)"

case "$REPO" in
  SilverSight)
    # Homarr
    if [ -f "$SECRETS_DIR/homarr-values.enc.yaml" ]; then
      log "Deploying Homarr..."
      sops --decrypt --output-type yaml "$SECRETS_DIR/homarr-values.enc.yaml" > /tmp/homarr-values.yaml
      helm upgrade --install homarr oci://ghcr.io/homarr-labs/charts/homarr \
        --namespace homarr \
        -f /tmp/homarr-values.yaml --wait --timeout 4m
      rm -f /tmp/homarr-values.yaml
      log "Homarr deployed ✅"
    fi

    # Authentik
    if [ -f "$SECRETS_DIR/authentik-values.enc.yaml" ]; then
      log "Deploying Authentik..."
      sops --decrypt --output-type yaml "$SECRETS_DIR/authentik-values.enc.yaml" > /tmp/authentik-values.yaml
      helm upgrade --install authentik oci://ghcr.io/goauthentik/helm-charts/authentik \
        --namespace authentik \
        -f /tmp/authentik-values.yaml --wait --timeout 8m
      rm -f /tmp/authentik-values.yaml
      log "Authentik deployed ✅"
    fi
    ;;
  *)
    log "No deploy handler for repo: $REPO"
    ;;
esac

log "Deploy complete."
