#!/usr/bin/env bash
# deploy-secrets.sh — Populate K8s secrets from Scaleway Secrets Manager.
# Usage: ./scripts/deploy-secrets.sh [--dry-run]
#
# Prerequisites:
#   - scw CLI configured (SCW_ACCESS_KEY, SCW_SECRET_KEY, SCW_DEFAULT_PROJECT_ID)
#   - kubectl configured for target cluster
#   - Scaleway secrets exist at paths: foxhunt/db-password, foxhunt/jwt-secret, etc.
#
# Scaleway secret paths (create these in SCW console or CLI):
#   foxhunt/db-password
#   foxhunt/jwt-secret
#   foxhunt/redis-password
#   foxhunt/s3-access-key
#   foxhunt/s3-secret-key

set -euo pipefail

NAMESPACE="foxhunt"
DRY_RUN=""

if [[ "${1:-}" == "--dry-run" ]]; then
  DRY_RUN="--dry-run=client"
  echo "DRY RUN — no changes will be applied"
fi

# Fetch a secret value from Scaleway Secrets Manager.
# Usage: scw_secret <path>
scw_secret() {
  local path="$1"
  scw secret version access-by-path name="$path" field=data --output json 2>/dev/null \
    | python3 -c "import sys,json; print(json.load(sys.stdin)['data'])" \
    || { echo "ERROR: Failed to fetch secret '$path' from Scaleway" >&2; exit 1; }
}

echo "Fetching secrets from Scaleway Secrets Manager..."

DB_PASSWORD=$(scw_secret "foxhunt/db-password")
JWT_SECRET=$(scw_secret "foxhunt/jwt-secret")
REDIS_PASSWORD=$(scw_secret "foxhunt/redis-password")
S3_ACCESS_KEY=$(scw_secret "foxhunt/s3-access-key")
S3_SECRET_KEY=$(scw_secret "foxhunt/s3-secret-key")

echo "Creating K8s secrets in namespace $NAMESPACE..."

# db-credentials
kubectl create secret generic db-credentials \
  --namespace="$NAMESPACE" \
  --from-literal=password="$DB_PASSWORD" \
  --save-config $DRY_RUN \
  -o yaml | kubectl apply -f - $DRY_RUN

# jwt-secret
kubectl create secret generic jwt-secret \
  --namespace="$NAMESPACE" \
  --from-literal=secret="$JWT_SECRET" \
  --save-config $DRY_RUN \
  -o yaml | kubectl apply -f - $DRY_RUN

# redis-credentials
kubectl create secret generic redis-credentials \
  --namespace="$NAMESPACE" \
  --from-literal=password="$REDIS_PASSWORD" \
  --save-config $DRY_RUN \
  -o yaml | kubectl apply -f - $DRY_RUN

# s3-credentials
kubectl create secret generic s3-credentials \
  --namespace="$NAMESPACE" \
  --from-literal=access-key="$S3_ACCESS_KEY" \
  --from-literal=secret-key="$S3_SECRET_KEY" \
  --save-config $DRY_RUN \
  -o yaml | kubectl apply -f - $DRY_RUN

echo "Done. Secrets created/updated in namespace $NAMESPACE."
echo ""
echo "Verify with: kubectl get secrets -n $NAMESPACE"
