#!/bin/bash
# ============================================================
# FalahOS SSO Credentials Setup Script
# ============================================================
# Run this on your Contabo VPS after getting OAuth credentials.
# It safely updates .env, rebuilds, and redeploys.
#
# Usage: bash /root/falah-mobile/scripts/setup-sso.sh
# ============================================================

set -e

SSO_DIR="$(cd "$(dirname "$0")/.." && pwd)"
ENV_FILE="$SSO_DIR/.env"
COMPOSE_FILE="$SSO_DIR/docker-compose.yml"

echo "╔═══════════════════════════════════════════════╗"
echo "║     FalahOS SSO Credentials Setup             ║"
echo "╚═══════════════════════════════════════════════╝"
echo ""

# --- Prompt for GitHub ---
echo "── 🐙 GitHub OAuth App ──"
read -p "  Client ID    : " GITHUB_CLIENT_ID
read -sp "  Client Secret: " GITHUB_CLIENT_SECRET
echo ""
echo ""

# --- Prompt for Google ---
echo "── 🔵 Google OAuth ──"
read -p "  Client ID    : " GOOGLE_CLIENT_ID
read -sp "  Client Secret: " GOOGLE_CLIENT_SECRET
echo ""
echo ""

# --- Confirm ---
echo "═══════════════════════════════════════════════"
echo "  Summary:"
echo "  GitHub:  ${GITHUB_CLIENT_ID:0:10}..."
echo "  Google:  ${GOOGLE_CLIENT_ID:0:10}..."
echo "═══════════════════════════════════════════════"
read -p "Apply these credentials and redeploy? (y/N) " CONFIRM

if [ "$CONFIRM" != "y" ] && [ "$CONFIRM" != "Y" ]; then
  echo "Aborted. No changes made."
  exit 0
fi

# --- Backup current .env ---
cp "$ENV_FILE" "$ENV_FILE.backup"
echo "✓ Backed up .env -> .env.backup"

# --- Remove old OAuth lines if they exist ---
sed -i '/^GOOGLE_CLIENT_ID=/d' "$ENV_FILE"
sed -i '/^GOOGLE_CLIENT_SECRET=/d' "$ENV_FILE"
sed -i '/^GITHUB_CLIENT_ID=/d' "$ENV_FILE"
sed -i '/^GITHUB_CLIENT_SECRET=/d' "$ENV_FILE"

# --- Append new credentials ---
cat >> "$ENV_FILE" << EOF

# --- OAuth / SSO ---
GOOGLE_CLIENT_ID="$GOOGLE_CLIENT_ID"
GOOGLE_CLIENT_SECRET="$GOOGLE_CLIENT_SECRET"
GITHUB_CLIENT_ID="$GITHUB_CLIENT_ID"
GITHUB_CLIENT_SECRET="$GITHUB_CLIENT_SECRET"
EOF

echo "✓ Credentials written to .env"

# --- Rebuild and deploy ---
echo ""
echo "═══ Building & Deploying ═══"
cd "$SSO_DIR"
npm run build

echo ""
echo "═══ Rebuilding Docker image ═══"
docker compose -f "$COMPOSE_FILE" build --pull

echo ""
echo "═══ Restarting container ═══"
docker compose -f "$COMPOSE_FILE" up -d --force-recreate

echo ""
echo "✓ SSO setup complete!"
echo "  Test at: https://falahos.my/mobile/auth"
