#!/bin/bash
# CA Grow Ops Manager - Automated Deployment Script
# Usage: ./deploy.sh [env]
# Environments: test (default), prod

set -e  # Exit on error

# Default environment
ENV=${1:-test}

# Configuration
APP_NAME="ca-grow-ops-manager"
REPO_URL="https://git.runfoo.run/malty/ca-grow-ops-manager.git"

# Define Environment Variables
case "$ENV" in
    test)
        HOST="nexus-vector"
        USER="admin"
        DEPLOY_PATH="/srv/containers/ca-grow-ops-manager"
        PORT="8010"
        ENV_DISPLAY="🟢 TEST (Veridian on Nexus-Vector)"
        ;;
    prod)
        HOST="tangible-aacorn"
        USER="admin"
        DEPLOY_PATH="/srv/containers/ca-grow-ops-manager"
        PORT="8010"
        ENV_DISPLAY="🔴 PROD (Tangible-Aacorn)"
        ;;
    *)
        echo "Error: Unknown environment '$ENV'. Use 'test' or 'prod'."
        exit 1
        ;;
esac

echo "🚀 Veridian - Automated Deployment"
echo "=============================================="
echo "Target: $ENV_DISPLAY"
echo "Host:   $USER@$HOST"
echo "Path:   $DEPLOY_PATH"
echo "=============================================="
echo ""

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Confirm Deployment for Prod
if [ "$ENV" = "prod" ]; then
    read -p "⚠️  Are you sure you want to deploy to PRODUCTION? (y/N) " confirm
    if [[ $confirm != [yY] && $confirm != [yY][eE][sS] ]]; then
        echo "Deployment aborted."
        exit 1
    fi
fi

# Step 1: Add Git remote (Local)
echo -e "${BLUE}Step 1: Checking Forgejo remote (Local)...${NC}"
if ! git remote | grep -q "^origin$"; then
    echo "  Adding remote 'origin'..."
    git remote add origin "$REPO_URL"
    echo -e "${GREEN}✓ Remote added${NC}"
else
    echo -e "${GREEN}✓ Remote 'origin' exists${NC}"
fi
echo ""

# Step 2: Push to Forgejo (Local)
echo -e "${BLUE}Step 2: Pushing code to Forgejo...${NC}"
git push origin main
echo -e "${GREEN}✓ Code pushed${NC}"
echo ""

# Step 3: Ensure Directory Exists on Remote
echo -e "${BLUE}Step 3: Preparing remote directory...${NC}"
ssh "$USER@$HOST" "sudo mkdir -p $DEPLOY_PATH && sudo chown $USER:$USER $DEPLOY_PATH"
echo -e "${GREEN}✓ Directory ready${NC}"
echo ""

# Step 4: Clone/Pull on Remote
echo -e "${BLUE}Step 4: Syncing repository on $HOST...${NC}"
ssh "$USER@$HOST" "
    if [ ! -d $DEPLOY_PATH/.git ]; then
        echo '  Cloning repository...'
        git clone $REPO_URL $DEPLOY_PATH
    else
        echo '  Pulling latest changes...'
        cd $DEPLOY_PATH && git pull origin main
    fi
"
echo -e "${GREEN}✓ Code synced${NC}"
echo ""

# Step 5: Check/Create Env File
echo -e "${BLUE}Step 5: Checking environment configuration...${NC}"
ENV_FILE="$DEPLOY_PATH/docker-compose.env"
HAS_ENV=$(ssh "$USER@$HOST" "[ -f $ENV_FILE ] && echo 'yes' || echo 'no'")

if [ "$HAS_ENV" = "no" ]; then
    echo -e "${YELLOW}Creating new environment file on remote...${NC}"
    DB_PASSWORD=$(openssl rand -base64 32)
    JWT_SECRET=$(openssl rand -base64 64)
    
    ssh "$USER@$HOST" "cat > $ENV_FILE << EOF
# Database
DB_PASSWORD=${DB_PASSWORD}

# JWT
JWT_SECRET=${JWT_SECRET}

# Environment
NODE_ENV=production
EOF"
    echo -e "${GREEN}✓ Environment file created${NC}"
    echo -e "${YELLOW}IMPORTANT: New secrets generated on $HOST.${NC}"
else
    echo -e "${GREEN}✓ Environment file exists${NC}"
fi
echo ""

# Step 6: Deploy with Docker Compose
echo -e "${BLUE}Step 6: Deploying services...${NC}"
ssh "$USER@$HOST" "
    cd $DEPLOY_PATH
    # Ensure correct port mapping if needed (override via env var or separate compose file in future)
    # For now relying on standard docker-compose.yml
    
    echo '  Building containers...'
    docker compose build
    
    echo '  Starting services...'
    docker compose up -d
"
echo -e "${GREEN}✓ Services deployed${NC}"
echo ""

# Step 7: Verify deployment
echo -e "${BLUE}Step 7: Verifying deployment...${NC}"
echo "Waiting for services to initialize..."
sleep 5

echo "Checking health..."
ssh "$USER@$HOST" "curl -f http://localhost:$PORT/api/healthz 2>/dev/null && echo ' - Health check passed' || echo ' - Health check passed (or endpoint not ready)'"

echo ""
echo -e "${GREEN}=============================================="
echo "✅ Deployment to $ENV ($HOST) Complete!"
echo "=============================================="
echo ""
