#!/bin/bash
#
# One-time CapRover setup: adds persistent directory for uploads.
# Run this ONCE from your local machine:
#   bash docker/caprover-setup.sh
#
# After this, uploads survive force deploys.
#

set -e

# ── Config (edit these) ──
CAPROVER_URL="${CAPROVER_URL:-https://captain.yourdomain.com}"
CAPROVER_APP="${CAPROVER_APP:-club-erp}"
CAPROVER_PASSWORD="${CAPROVER_PASSWORD:-}"

echo "=== CapRover Persistent Storage Setup ==="
echo ""

if [ -z "$CAPROVER_URL" ] || [ "$CAPROVER_URL" = "https://captain.yourdomain.com" ]; then
    read -p "CapRover URL (e.g. https://captain.yourdomain.com): " CAPROVER_URL
fi

if [ -z "$CAPROVER_APP" ] || [ "$CAPROVER_APP" = "club-erp" ]; then
    read -p "App name in CapRover: " CAPROVER_APP
fi

if [ -z "$CAPROVER_PASSWORD" ]; then
    read -sp "CapRover password: " CAPROVER_PASSWORD
    echo ""
fi

echo ""
echo "URL: $CAPROVER_URL"
echo "App: $CAPROVER_APP"
echo ""

# ── Get auth token ──
echo "Authenticating..."
TOKEN=$(curl -s -X POST "$CAPROVER_URL/api/v2/login" \
    -H "Content-Type: application/json" \
    -H "x-namespace: captain" \
    -d "{\"password\":\"$CAPROVER_PASSWORD\"}" | python3 -c "import sys,json; print(json.load(sys.stdin).get('data',{}).get('token',''))" 2>/dev/null)

if [ -z "$TOKEN" ]; then
    echo "ERROR: Failed to authenticate. Check URL and password."
    exit 1
fi
echo "Authenticated!"

# ── Get current app definition ──
echo "Fetching app definition..."
APP_DEF=$(curl -s -X GET "$CAPROVER_URL/api/v2/user/apps/appDefinitions" \
    -H "Content-Type: application/json" \
    -H "x-namespace: captain" \
    -H "x-captain-auth: $TOKEN")

# ── Add persistent directory ──
echo "Adding persistent directory: /var/www/html/storage/uploads"

UPDATE_RESULT=$(curl -s -X POST "$CAPROVER_URL/api/v2/user/apps/appDefinitions/update" \
    -H "Content-Type: application/json" \
    -H "x-namespace: captain" \
    -H "x-captain-auth: $TOKEN" \
    -d "{
        \"appName\": \"$CAPROVER_APP\",
        \"volumes\": [
            {
                \"containerPath\": \"/var/www/html/storage/uploads\",
                \"volumeName\": \"${CAPROVER_APP}-uploads\"
            }
        ]
    }")

# Check result
STATUS=$(echo "$UPDATE_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('status',0))" 2>/dev/null)

if [ "$STATUS" = "100" ]; then
    echo ""
    echo "=== SUCCESS ==="
    echo "Persistent volume '${CAPROVER_APP}-uploads' mapped to /var/www/html/storage/uploads"
    echo ""
    echo "Next force deploy will use this volume. Uploads will persist across deploys."
else
    echo ""
    echo "=== RESPONSE ==="
    echo "$UPDATE_RESULT" | python3 -m json.tool 2>/dev/null || echo "$UPDATE_RESULT"
    echo ""
    echo "If this failed, try the alternative method below."
    echo ""
    echo "=== ALTERNATIVE: Manual API call ==="
    echo "curl -X POST '$CAPROVER_URL/api/v2/user/apps/appDefinitions/update' \\"
    echo "  -H 'Content-Type: application/json' \\"
    echo "  -H 'x-namespace: captain' \\"
    echo "  -H 'x-captain-auth: YOUR_TOKEN' \\"
    echo "  -d '{\"appName\":\"$CAPROVER_APP\",\"volumes\":[{\"containerPath\":\"/var/www/html/storage/uploads\",\"volumeName\":\"${CAPROVER_APP}-uploads\"}]}'"
fi
