#!/bin/bash

# Setup GitHub Actions secrets for VPS deployment
# This script encodes all .env files and Firebase configs as base64
# and pushes them to GitHub repository secrets

set -e

cd "$(dirname "$0")/.."
REPO_ROOT="$(pwd)"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${YELLOW}🔐 GitHub Actions Secrets Setup${NC}"
echo "Repository: $REPO_ROOT"
echo ""

# Verify GitHub CLI is installed
if ! command -v gh &> /dev/null; then
    echo -e "${RED}❌ GitHub CLI not found. Install it: https://cli.github.com${NC}"
    exit 1
fi

# Verify we're authenticated
if ! gh auth status &> /dev/null; then
    echo -e "${RED}❌ Not authenticated with GitHub. Run: gh auth login${NC}"
    exit 1
fi

echo -e "${GREEN}✓ GitHub CLI authenticated${NC}"
echo ""

# Function to set a secret
set_secret() {
    local name="$1"
    local value="$2"
    
    if [ -z "$value" ]; then
        echo -e "${YELLOW}⊘ Skipping $name (empty value)${NC}"
        return
    fi
    
    echo "$value" | gh secret set "$name" --body=-
    echo -e "${GREEN}✓ Set $name${NC}"
}

# Function to encode file to base64
encode_file() {
    local file="$1"
    if [ ! -f "$file" ]; then
        echo -e "${YELLOW}⊘ File not found: $file${NC}"
        return ""
    fi
    cat "$file" | base64
}

# Function to encode directory to tar.gz base64
encode_dir() {
    local dir="$1"
    if [ ! -d "$dir" ]; then
        echo -e "${YELLOW}⊘ Directory not found: $dir${NC}"
        return ""
    fi
    tar -czf - -C "$(dirname "$dir")" "$(basename "$dir")" | base64
}

echo -e "${YELLOW}📝 Encoding environment files...${NC}"

# Root environment files
ENV_ROOT_B64=$(encode_file ".env")
ENV_ROOT_DEV_B64=$(encode_file ".env.development")

# Create .env.production for backend if not exists
if [ ! -f ".env.production" ]; then
    echo -e "${YELLOW}⊘ Creating .env.production from .env${NC}"
    cp .env .env.production
fi
ENV_PRODUCTION_B64=$(encode_file ".env.production")

# App environment files
ENV_API_B64=$(encode_file "apps/api/.env")
ENV_WEB_B64=$(encode_file "apps/web/.env")

# Service account and Firebase
SERVICE_ACCOUNT_B64=$(encode_file "firebase/serviceAccount.json")
FIREBASE_TAR_B64=$(encode_dir "firebase")

echo -e "${YELLOW}📝 Encoding SSH key...${NC}"

# SSH key for deployment
if [ ! -f "$HOME/.ssh/myroadtrip_ci" ]; then
    echo -e "${YELLOW}⚠️  SSH key not found at ~/.ssh/myroadtrip_ci${NC}"
    echo -e "${YELLOW}   Generate one first: ssh-keygen -t ed25519 -f ~/.ssh/myroadtrip_ci -N ''${NC}"
    echo -e "${YELLOW}   Then add the public key to your VPS: ssh-copy-id -i ~/.ssh/myroadtrip_ci.pub ubuntu@vps-4d8abcb7.vps.ovh.net${NC}"
    exit 1
fi
VPS_SSH_KEY=$(cat "$HOME/.ssh/myroadtrip_ci")

echo ""
echo -e "${YELLOW}📤 Pushing secrets to GitHub...${NC}"

# VPS configuration secrets
set_secret "VPS_HOST" "vps-4d8abcb7.vps.ovh.net"
set_secret "VPS_USER" "ubuntu"
set_secret "VPS_SSH_PORT" "22"
set_secret "VPS_SSH_KEY" "$VPS_SSH_KEY"
set_secret "VPS_DEPLOY_PATH" "/srv/myroadtrip"
set_secret "VPS_API_HEALTHCHECK_URL" "https://api.roadtripper.io/health"
set_secret "VPS_WEB_HEALTHCHECK_URL" "https://roadtripper.io/"

# Environment file secrets (base64 encoded)
set_secret "ENV_ROOT_B64" "$ENV_ROOT_B64"
set_secret "ENV_ROOT_DEV_B64" "$ENV_ROOT_DEV_B64"
set_secret "ENV_PRODUCTION_B64" "$ENV_PRODUCTION_B64"
set_secret "ENV_API_B64" "$ENV_API_B64"
set_secret "ENV_WEB_B64" "$ENV_WEB_B64"

# Firebase secrets
set_secret "SERVICE_ACCOUNT_B64" "$SERVICE_ACCOUNT_B64"
set_secret "FIREBASE_TAR_B64" "$FIREBASE_TAR_B64"

echo ""
echo -e "${GREEN}✅ All secrets configured!${NC}"
echo ""
echo -e "${YELLOW}📋 Next steps:${NC}"
echo "  1. Verify secrets: gh secret list"
echo "  2. Trigger deployment: git push origin main"
echo "     OR manually trigger: gh workflow run deploy.yml --ref main"
echo ""
