#!/bin/bash
# ==============================================
# Deployment Script for Dev/Prod Environments
# ==============================================

set -e

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

# Parse arguments
ENV=${1:-dev}
CONFIG_FILE=".end.${ENV}"

if [ ! -f "$CONFIG_FILE" ]; then
    echo -e "${RED}Error: Configuration file $CONFIG_FILE not found${NC}"
    exit 1
fi

echo -e "${GREEN}Loading configuration from $CONFIG_FILE...${NC}"
source "$CONFIG_FILE"

# Set variables based on environment
if [ "$ENV" = "dev" ]; then
    HOST=$DEV_HOST
    USER=$DEV_USER
    PATH=$DEV_PATH
    PORT_WEB=$DEV_PORT_WEB
elif [ "$ENV" = "prod" ]; then
    HOST=$PROD_HOST
    USER=$PROD_USER
    PATH=$PROD_PATH
    PORT_WEB=$PROD_PORT_WEB
else
    echo -e "${RED}Error: Unknown environment $ENV${NC}"
    exit 1
fi

echo -e "${GREEN}Deploying to $ENV environment...${NC}"
echo -e "Host: ${YELLOW}$HOST${NC}"
echo -e "Path: ${YELLOW}$PATH${NC}"

# SSH deployment
ssh -o StrictHostKeyChecking=no ${USER}@${HOST} << EOF
    set -e
    cd ${PATH}
    
    echo "📦 Pulling latest changes..."
    git pull origin main || git pull origin master || git pull origin develop || true
    
    if [ "$BACKUP_BEFORE_DEPLOY" = "true" ] && [ "$ENV" = "prod" ]; then
        echo "💾 Creating database backup..."
        mkdir -p ${BACKUP_PATH}
        docker compose exec -T db pg_dump -U ${POSTGRES_USER} ${POSTGRES_DB} > ${BACKUP_PATH}/backup_\$(date +%Y%m%d_%H%M%S).sql || true
    fi
    
    echo "🛑 Stopping services..."
    docker compose down --timeout 30 || true
    
    echo "🔨 Building images..."
    docker compose build --no-cache
    
    echo "🚀 Starting services..."
    docker compose up -d
    
    echo "⏳ Waiting for services to be ready..."
    sleep 15
    
    if [ "$AUTO_MIGRATE" = "true" ]; then
        echo "📊 Running migrations..."
        docker compose exec -T web python manage.py migrate || true
    fi
    
    if [ "$AUTO_COLLECTSTATIC" = "true" ]; then
        echo "📁 Collecting static files..."
        docker compose exec -T web python manage.py collectstatic --noinput || true
    fi
    
    if [ "$RESTART_AFTER_DEPLOY" = "true" ]; then
        echo "🔄 Restarting services..."
        docker compose restart
    fi
    
    echo "✅ Deployment completed!"
    
    echo "🏥 Running health check..."
    sleep 10
    docker compose ps
    curl -f ${HEALTH_CHECK_URL} || echo "⚠️  Health check failed"
EOF

echo -e "${GREEN}✅ Deployment to $ENV completed successfully!${NC}"
