#!/bin/bash
# inject-secrets.sh
# Writes secrets to the secrets directory for K8s-style secret mounting
#
# Supports two modes:
# 1. GitLab CI: File variables provide PATH to temp file
# 2. Gitea Actions: Environment variables contain the secret value directly
#
# Required environment variables:
#   - POSTGRES_PASSWORD
#   - AUTH0_CLIENT_SECRET
#   - AUTH0_MANAGEMENT_CLIENT_ID
#   - AUTH0_MANAGEMENT_CLIENT_SECRET
#   - GOOGLE_MAPS_API_KEY
#   - GOOGLE_MAPS_MAP_ID
#   - CF_DNS_API_TOKEN
#   - RESEND_API_KEY
#   - STRIPE_SECRET_KEY
#   - STRIPE_WEBHOOK_SECRET

set -euo pipefail

# Configuration
DEPLOY_PATH="${DEPLOY_PATH:-/opt/motovaultpro}"
SECRETS_DIR="${SECRETS_DIR:-${DEPLOY_PATH}/secrets/app}"

# List of all secret files (must match docker-compose volume mounts)
SECRET_FILES=(
    "postgres-password.txt"
    "auth0-client-secret.txt"
    "auth0-management-client-id.txt"
    "auth0-management-client-secret.txt"
    "google-maps-api-key.txt"
    "google-maps-map-id.txt"
    "cloudflare-dns-token.txt"
    "resend-api-key.txt"
    "stripe-secret-key.txt"
    "stripe-webhook-secret.txt"
)

echo "Injecting secrets..."
echo "  Deploy path: $DEPLOY_PATH"
echo "  Secrets dir: $SECRETS_DIR"

# Step 1: Clean up any incorrectly created directories
# Docker creates directories when bind-mounting files that don't exist
echo ""
echo "Cleaning up any corrupted secret paths..."
for file in "${SECRET_FILES[@]}"; do
    target_path="${SECRETS_DIR}/${file}"
    if [ -d "$target_path" ]; then
        echo "  Removing directory: $file"
        rm -rf "$target_path"
    fi
done

# Step 2: Ensure secrets directory exists
if [ -e "$SECRETS_DIR" ] && [ ! -d "$SECRETS_DIR" ]; then
    echo "  Removing invalid secrets path..."
    rm -rf "$SECRETS_DIR"
fi
mkdir -p "$SECRETS_DIR"
chmod 700 "$SECRETS_DIR"

# Function to inject a secret
# Supports both:
#   - Direct value (Gitea Actions): VAR contains the secret
#   - File path (GitLab CI): VAR contains path to file with secret
inject_secret() {
    local var_name="$1"
    local file_name="$2"
    local target_path="${SECRETS_DIR}/${file_name}"

    local source_value="${!var_name:-}"

    if [ -z "$source_value" ]; then
        echo "  ERROR: Variable $var_name is not set"
        return 1
    fi

    # Check if it's a file path (GitLab CI File variable)
    if [[ "$source_value" =~ ^/ ]] && [ -f "$source_value" ]; then
        # GitLab mode: copy from file
        cp "$source_value" "$target_path"
        echo "  OK: $file_name (from file)"
    else
        # Gitea mode: write value directly
        echo -n "$source_value" > "$target_path"
        echo "  OK: $file_name (from env)"
    fi

    chmod 644 "$target_path"
}

# Inject all secrets
FAILED=0

inject_secret "POSTGRES_PASSWORD" "postgres-password.txt" || FAILED=1
inject_secret "AUTH0_CLIENT_SECRET" "auth0-client-secret.txt" || FAILED=1
inject_secret "AUTH0_MANAGEMENT_CLIENT_ID" "auth0-management-client-id.txt" || FAILED=1
inject_secret "AUTH0_MANAGEMENT_CLIENT_SECRET" "auth0-management-client-secret.txt" || FAILED=1
inject_secret "GOOGLE_MAPS_API_KEY" "google-maps-api-key.txt" || FAILED=1
inject_secret "GOOGLE_MAPS_MAP_ID" "google-maps-map-id.txt" || FAILED=1
inject_secret "CF_DNS_API_TOKEN" "cloudflare-dns-token.txt" || FAILED=1
inject_secret "RESEND_API_KEY" "resend-api-key.txt" || FAILED=1
inject_secret "STRIPE_SECRET_KEY" "stripe-secret-key.txt" || FAILED=1
inject_secret "STRIPE_WEBHOOK_SECRET" "stripe-webhook-secret.txt" || FAILED=1

if [ $FAILED -eq 1 ]; then
    echo ""
    echo "ERROR: One or more secrets failed to inject"
    exit 1
fi

echo ""
echo "Secrets injected successfully"
echo "Files created in $SECRETS_DIR:"
ls -la "$SECRETS_DIR"
