#!/bin/bash
# Automated deployment script for GuruConnect
# Called by CI/CD pipeline or manually
# Usage: ./deploy.sh [package_file.tar.gz]

set -e

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo "========================================="
echo "GuruConnect Deployment Script"
echo "========================================="
echo ""

# Configuration
DEPLOY_DIR="/home/guru/guru-connect"
BACKUP_DIR="/home/guru/deployments/backups"
ARTIFACT_DIR="/home/guru/deployments/artifacts"
TIMESTAMP=$(date +%Y%m%d-%H%M%S)

# Detect package file
if [ -n "$1" ]; then
    PACKAGE_FILE="$1"
elif [ -f "/tmp/guruconnect-server-latest.tar.gz" ]; then
    PACKAGE_FILE="/tmp/guruconnect-server-latest.tar.gz"
else
    echo -e "${RED}ERROR: No deployment package specified${NC}"
    echo "Usage: $0 <package_file.tar.gz>"
    exit 1
fi

if [ ! -f "$PACKAGE_FILE" ]; then
    echo -e "${RED}ERROR: Package file not found: $PACKAGE_FILE${NC}"
    exit 1
fi

echo "Package: $PACKAGE_FILE"
echo "Target: $DEPLOY_DIR"
echo ""

# Create backup and artifact directories
mkdir -p "$BACKUP_DIR"
mkdir -p "$ARTIFACT_DIR"

# Backup current binary
echo "Creating backup..."
if [ -f "$DEPLOY_DIR/target/x86_64-unknown-linux-gnu/release/guruconnect-server" ]; then
    cp "$DEPLOY_DIR/target/x86_64-unknown-linux-gnu/release/guruconnect-server" \
       "$BACKUP_DIR/guruconnect-server-${TIMESTAMP}"
    echo -e "${GREEN}Backup created: ${BACKUP_DIR}/guruconnect-server-${TIMESTAMP}${NC}"
else
    echo -e "${YELLOW}No existing binary to backup${NC}"
fi

# Stop service
echo ""
echo "Stopping GuruConnect service..."
if sudo systemctl is-active --quiet guruconnect; then
    sudo systemctl stop guruconnect
    echo -e "${GREEN}Service stopped${NC}"
else
    echo -e "${YELLOW}Service not running${NC}"
fi

# Extract new binary
echo ""
echo "Extracting deployment package..."
TEMP_EXTRACT="/tmp/guruconnect-deploy-${TIMESTAMP}"
mkdir -p "$TEMP_EXTRACT"
tar -xzf "$PACKAGE_FILE" -C "$TEMP_EXTRACT"

# Deploy binary
echo "Deploying new binary..."
if [ -f "$TEMP_EXTRACT/guruconnect-server" ]; then
    mkdir -p "$DEPLOY_DIR/target/x86_64-unknown-linux-gnu/release"
    cp "$TEMP_EXTRACT/guruconnect-server" \
       "$DEPLOY_DIR/target/x86_64-unknown-linux-gnu/release/guruconnect-server"
    chmod +x "$DEPLOY_DIR/target/x86_64-unknown-linux-gnu/release/guruconnect-server"
    echo -e "${GREEN}Binary deployed${NC}"
else
    echo -e "${RED}ERROR: Binary not found in package${NC}"
    exit 1
fi

# Deploy static files if present
if [ -d "$TEMP_EXTRACT/static" ]; then
    echo "Deploying static files..."
    cp -r "$TEMP_EXTRACT/static" "$DEPLOY_DIR/server/"
    echo -e "${GREEN}Static files deployed${NC}"
fi

# Deploy migrations if present
if [ -d "$TEMP_EXTRACT/migrations" ]; then
    echo "Deploying database migrations..."
    cp -r "$TEMP_EXTRACT/migrations" "$DEPLOY_DIR/server/"
    echo -e "${GREEN}Migrations deployed${NC}"
fi

# Save artifact
echo ""
echo "Archiving deployment package..."
cp "$PACKAGE_FILE" "$ARTIFACT_DIR/guruconnect-server-${TIMESTAMP}.tar.gz"
ln -sf "$ARTIFACT_DIR/guruconnect-server-${TIMESTAMP}.tar.gz" \
       "$ARTIFACT_DIR/guruconnect-server-latest.tar.gz"
echo -e "${GREEN}Artifact saved${NC}"

# Cleanup temp directory
rm -rf "$TEMP_EXTRACT"

# Start service
echo ""
echo "Starting GuruConnect service..."
sudo systemctl start guruconnect
sleep 2

# Verify service started
if sudo systemctl is-active --quiet guruconnect; then
    echo -e "${GREEN}Service started successfully${NC}"
else
    echo -e "${RED}ERROR: Service failed to start${NC}"
    echo "Rolling back to previous version..."

    # Rollback
    if [ -f "$BACKUP_DIR/guruconnect-server-${TIMESTAMP}" ]; then
        cp "$BACKUP_DIR/guruconnect-server-${TIMESTAMP}" \
           "$DEPLOY_DIR/target/x86_64-unknown-linux-gnu/release/guruconnect-server"
        sudo systemctl start guruconnect
        echo -e "${YELLOW}Rolled back to previous version${NC}"
    fi

    echo "Check logs: sudo journalctl -u guruconnect -n 50"
    exit 1
fi

# Health check
echo ""
echo "Running health check..."
sleep 2
if curl -s http://172.16.3.30:3002/health | grep -q "OK"; then
    echo -e "${GREEN}Health check: PASSED${NC}"
else
    echo -e "${YELLOW}WARNING: Health check failed${NC}"
    echo "Service may still be starting up..."
fi

# Get version info
echo ""
echo "Deployment version information:"
VERSION=$($DEPLOY_DIR/target/x86_64-unknown-linux-gnu/release/guruconnect-server --version 2>/dev/null || echo "Version info not available")
echo "$VERSION"

echo ""
echo "========================================="
echo "Deployment Complete!"
echo "========================================="
echo ""
echo "Deployment time: $TIMESTAMP"
echo "Backup location: $BACKUP_DIR/guruconnect-server-${TIMESTAMP}"
echo "Artifact location: $ARTIFACT_DIR/guruconnect-server-${TIMESTAMP}.tar.gz"
echo ""
echo "Service status:"
sudo systemctl status guruconnect --no-pager | head -15
echo ""
echo "To view logs: sudo journalctl -u guruconnect -f"
echo "To rollback: cp $BACKUP_DIR/guruconnect-server-${TIMESTAMP} target/x86_64-unknown-linux-gnu/release/guruconnect-server && sudo systemctl restart guruconnect"
echo ""
