#!/bin/bash
# ============================================
# FLOWBOT DCI - AUTOMATED DEPLOYMENT SCRIPT
# ============================================
# Deploys v2 to production server via rsync/SSH
#
# Usage: ./deploy.sh [--dry-run]
# ============================================

set -e

# Configuration
REMOTE_HOST="159-100-13-177.cprapid.com"
REMOTE_USER="root"
REMOTE_PORT="22"
REMOTE_PATH="/home/digupdog/public_html/flowb0t.com/v2"
LOCAL_PATH="$(dirname "$0")/.."

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

# Check for dry-run flag
DRY_RUN=""
if [ "$1" == "--dry-run" ]; then
    DRY_RUN="--dry-run"
    echo -e "${YELLOW}DRY RUN MODE - No changes will be made${NC}"
fi

echo -e "${GREEN}======================================${NC}"
echo -e "${GREEN}  FLOWBOT DCI - DEPLOYMENT SCRIPT    ${NC}"
echo -e "${GREEN}======================================${NC}"
echo ""
echo "Local:  $LOCAL_PATH"
echo "Remote: $REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH"
echo ""

# Files/directories to exclude from deployment
EXCLUDES=(
    ".env"
    ".git"
    ".gitignore"
    "error_log"
    "temp/"
    "logs/*.log"
    "debug_*.html"
    "*.tmp"
    "*.bak"
    "deploy/deploy.sh"
    "node_modules/"
    ".vscode/"
    "*.pyc"
    "__pycache__/"
)

# Build exclude arguments
EXCLUDE_ARGS=""
for exclude in "${EXCLUDES[@]}"; do
    EXCLUDE_ARGS="$EXCLUDE_ARGS --exclude='$exclude'"
done

# Step 1: Pre-deployment checks
echo -e "${YELLOW}Step 1: Running pre-deployment checks...${NC}"

# Check if rsync is available
if ! command -v rsync &> /dev/null; then
    echo -e "${RED}ERROR: rsync not found. Please install rsync.${NC}"
    exit 1
fi

# Check if ssh is available
if ! command -v ssh &> /dev/null; then
    echo -e "${RED}ERROR: ssh not found. Please install OpenSSH.${NC}"
    exit 1
fi

echo -e "${GREEN}Pre-deployment checks passed${NC}"
echo ""

# Step 2: Create backup on remote (if not dry-run)
if [ -z "$DRY_RUN" ]; then
    echo -e "${YELLOW}Step 2: Creating remote backup...${NC}"
    BACKUP_NAME="backup_$(date +%Y%m%d_%H%M%S).tar.gz"
    ssh -p $REMOTE_PORT $REMOTE_USER@$REMOTE_HOST "cd /home/digupdog/public_html/flowb0t.com && tar -czf /home/digupdog/backups/$BACKUP_NAME v2/ 2>/dev/null || echo 'No existing v2 to backup'"
    echo -e "${GREEN}Backup created: $BACKUP_NAME${NC}"
else
    echo -e "${YELLOW}Step 2: Skipping backup (dry-run)${NC}"
fi
echo ""

# Step 3: Deploy files
echo -e "${YELLOW}Step 3: Deploying files...${NC}"
echo "Syncing files with rsync..."

# Build rsync command
RSYNC_CMD="rsync -avz --progress --delete $DRY_RUN \
    --exclude='.env' \
    --exclude='.git' \
    --exclude='.gitignore' \
    --exclude='error_log' \
    --exclude='temp/' \
    --exclude='logs/*.log' \
    --exclude='debug_*.html' \
    --exclude='*.tmp' \
    --exclude='*.bak' \
    --exclude='node_modules/' \
    --exclude='.vscode/' \
    -e 'ssh -p $REMOTE_PORT' \
    '$LOCAL_PATH/' '$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH/'"

# Execute rsync
eval $RSYNC_CMD

echo -e "${GREEN}Files deployed successfully${NC}"
echo ""

# Step 4: Set permissions
if [ -z "$DRY_RUN" ]; then
    echo -e "${YELLOW}Step 4: Setting file permissions...${NC}"
    ssh -p $REMOTE_PORT $REMOTE_USER@$REMOTE_HOST "chmod -R 755 $REMOTE_PATH && chmod -R 777 $REMOTE_PATH/temp $REMOTE_PATH/logs 2>/dev/null || true"
    echo -e "${GREEN}Permissions set${NC}"
else
    echo -e "${YELLOW}Step 4: Skipping permissions (dry-run)${NC}"
fi
echo ""

# Step 5: Copy .env if needed
if [ -z "$DRY_RUN" ]; then
    echo -e "${YELLOW}Step 5: Checking .env file...${NC}"
    ssh -p $REMOTE_PORT $REMOTE_USER@$REMOTE_HOST "test -f $REMOTE_PATH/.env || cp $REMOTE_PATH/.env.example $REMOTE_PATH/.env 2>/dev/null || echo '.env already exists or example not found'"
    echo -e "${GREEN}.env checked${NC}"
else
    echo -e "${YELLOW}Step 5: Skipping .env check (dry-run)${NC}"
fi
echo ""

# Step 6: Run migrations if needed
if [ -z "$DRY_RUN" ]; then
    echo -e "${YELLOW}Step 6: Running migrations (if any)...${NC}"
    ssh -p $REMOTE_PORT $REMOTE_USER@$REMOTE_HOST "cd $REMOTE_PATH && php deploy/install_v7.php migrate 2>/dev/null || echo 'No migrations to run'"
    echo -e "${GREEN}Migrations completed${NC}"
else
    echo -e "${YELLOW}Step 6: Skipping migrations (dry-run)${NC}"
fi
echo ""

# Done
echo -e "${GREEN}======================================${NC}"
echo -e "${GREEN}  DEPLOYMENT COMPLETED SUCCESSFULLY  ${NC}"
echo -e "${GREEN}======================================${NC}"
echo ""
echo "Deployed to: https://flowb0t.com/v2/"
echo ""
if [ -n "$DRY_RUN" ]; then
    echo -e "${YELLOW}This was a dry-run. Run without --dry-run to deploy.${NC}"
fi
