#!/bin/bash

# ChaseDaddy.ai Deployment Script for InMotion Hosting
# This script automates the deployment process on a Linux dedicated server

set -e  # Exit on any error

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

# Configuration
APP_NAME="chasedaddy.ai"
DEPLOY_DIR="/var/www/chasedaddy.ai"
DOMAIN="chasedaddy.ai"
CLIENT_PORT=3001
SERVER_PORT=3002

echo -e "${GREEN}================================${NC}"
echo -e "${GREEN}ChaseDaddy.ai Deployment Script${NC}"
echo -e "${GREEN}================================${NC}"
echo ""

# Function to print colored output
print_status() {
    echo -e "${GREEN}[✓]${NC} $1"
}

print_error() {
    echo -e "${RED}[✗]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[!]${NC} $1"
}

# Check if running as root or with sudo
if [ "$EUID" -ne 0 ]; then
    print_warning "This script should be run with sudo privileges for some operations."
    print_warning "You may be prompted for your password."
fi

# Detect Linux distribution
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$ID
    VER=$VERSION_ID
    print_status "Detected OS: $OS $VER"
else
    print_error "Cannot detect OS version"
    exit 1
fi

# Set package manager based on OS
if [[ "$OS" == "centos" ]] || [[ "$OS" == "rhel" ]] || [[ "$OS" == "fedora" ]]; then
    PKG_MANAGER="yum"
    WEB_SERVER="httpd"
elif [[ "$OS" == "ubuntu" ]] || [[ "$OS" == "debian" ]]; then
    PKG_MANAGER="apt"
    WEB_SERVER="apache2"
else
    print_warning "Unknown OS: $OS. Assuming Debian-based."
    PKG_MANAGER="apt"
    WEB_SERVER="apache2"
fi

# Function to check if a command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Step 1: Update system
echo ""
echo -e "${YELLOW}Step 1: Updating system packages...${NC}"
if [ "$PKG_MANAGER" == "yum" ]; then
    sudo yum update -y
else
    sudo apt update && sudo apt upgrade -y
fi
print_status "System updated"

# Step 2: Install Node.js if not installed
echo ""
echo -e "${YELLOW}Step 2: Checking Node.js installation...${NC}"
if ! command_exists node; then
    print_warning "Node.js not found. Installing Node.js 20..."
    if [ "$PKG_MANAGER" == "yum" ]; then
        curl -fsSL https://rpm.nodesource.com/setup_20.x | sudo bash -
        sudo yum install -y nodejs
    else
        curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
        sudo apt-get install -y nodejs
    fi
    print_status "Node.js installed: $(node --version)"
else
    print_status "Node.js already installed: $(node --version)"
fi

# Step 3: Install Git if not installed
echo ""
echo -e "${YELLOW}Step 3: Checking Git installation...${NC}"
if ! command_exists git; then
    print_warning "Git not found. Installing..."
    sudo $PKG_MANAGER install -y git
    print_status "Git installed: $(git --version)"
else
    print_status "Git already installed: $(git --version)"
fi

# Step 4: Install PM2 if not installed
echo ""
echo -e "${YELLOW}Step 4: Checking PM2 installation...${NC}"
if ! command_exists pm2; then
    print_warning "PM2 not found. Installing..."
    sudo npm install -g pm2
    print_status "PM2 installed"
else
    print_status "PM2 already installed"
fi

# Step 5: Create deployment directory
echo ""
echo -e "${YELLOW}Step 5: Setting up deployment directory...${NC}"
if [ ! -d "$DEPLOY_DIR" ]; then
    sudo mkdir -p "$DEPLOY_DIR"
    sudo chown -R $USER:$USER "$DEPLOY_DIR"
    print_status "Created directory: $DEPLOY_DIR"
else
    print_status "Directory already exists: $DEPLOY_DIR"
fi

# Step 6: Clone or update repository
echo ""
echo -e "${YELLOW}Step 6: Repository setup...${NC}"
echo "Choose an option:"
echo "1) Clone from GitHub"
echo "2) Files already uploaded (skip)"
read -p "Enter choice [1-2]: " repo_choice

if [ "$repo_choice" == "1" ]; then
    read -p "Enter GitHub repository URL: " repo_url
    if [ -d "$DEPLOY_DIR/.git" ]; then
        print_warning "Git repository already exists. Pulling latest changes..."
        cd "$DEPLOY_DIR"
        git pull
    else
        print_warning "Cloning repository..."
        git clone "$repo_url" "$DEPLOY_DIR"
    fi
    print_status "Repository ready"
fi

# Step 7: Install dependencies
echo ""
echo -e "${YELLOW}Step 7: Installing application dependencies...${NC}"
cd "$DEPLOY_DIR"

if [ -d "client" ]; then
    print_warning "Installing client dependencies..."
    cd client
    npm install
    print_status "Client dependencies installed"
else
    print_error "Client directory not found!"
    exit 1
fi

if [ -d "$DEPLOY_DIR/server" ]; then
    print_warning "Installing server dependencies..."
    cd "$DEPLOY_DIR/server"
    npm install
    print_status "Server dependencies installed"
fi

# Step 8: Configure environment variables
echo ""
echo -e "${YELLOW}Step 8: Environment variable configuration...${NC}"
echo "You need to configure environment variables manually."
echo ""
print_warning "Create $DEPLOY_DIR/client/.env.local with:"
echo "NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co"
echo "NEXT_PUBLIC_SUPABASE_ANON_KEY=your_anon_key"
echo "NEXT_PUBLIC_BASE_URL=https://$DOMAIN"
echo "NODE_ENV=production"
echo ""
print_warning "Create $DEPLOY_DIR/server/.env with:"
echo "SUPABASE_URL=https://your-project.supabase.co"
echo "SUPABASE_SERVICE_KEY=your_service_key"
echo "NODE_ENV=production"
echo "PORT=$SERVER_PORT"
echo ""
read -p "Press Enter once you've created the .env files..."

# Verify .env files exist
if [ ! -f "$DEPLOY_DIR/client/.env.local" ]; then
    print_error "Client .env.local not found!"
    exit 1
fi
print_status "Environment variables configured"

# Step 9: Build application
echo ""
echo -e "${YELLOW}Step 9: Building Next.js application...${NC}"
cd "$DEPLOY_DIR/client"
npm run build
print_status "Application built successfully"

# Step 10: Create PM2 ecosystem file
echo ""
echo -e "${YELLOW}Step 10: Creating PM2 configuration...${NC}"
cat > "$DEPLOY_DIR/ecosystem.config.js" << EOF
module.exports = {
  apps: [
    {
      name: 'chasedaddy-client',
      cwd: '$DEPLOY_DIR/client',
      script: 'npm',
      args: 'start',
      env: {
        NODE_ENV: 'production',
        PORT: $CLIENT_PORT
      },
      instances: 1,
      autorestart: true,
      watch: false,
      max_memory_restart: '1G',
      error_file: '$DEPLOY_DIR/logs/client-error.log',
      out_file: '$DEPLOY_DIR/logs/client-out.log',
      log_file: '$DEPLOY_DIR/logs/client-combined.log',
      time: true
    }
  ]
};
EOF

# Add server if it exists
if [ -d "$DEPLOY_DIR/server" ]; then
    cat >> "$DEPLOY_DIR/ecosystem.config.js" << EOF

  apps.push({
    name: 'chasedaddy-server',
    cwd: '$DEPLOY_DIR/server',
    script: 'npm',
    args: 'start',
    env: {
      NODE_ENV: 'production',
      PORT: $SERVER_PORT
    },
    instances: 1,
    autorestart: true,
    watch: false,
    max_memory_restart: '1G',
    error_file: '$DEPLOY_DIR/logs/server-error.log',
    out_file: '$DEPLOY_DIR/logs/server-out.log',
    log_file: '$DEPLOY_DIR/logs/server-combined.log',
    time: true
  });
EOF
fi

print_status "PM2 configuration created"

# Step 11: Create logs directory
mkdir -p "$DEPLOY_DIR/logs"
print_status "Logs directory created"

# Step 12: Start applications with PM2
echo ""
echo -e "${YELLOW}Step 11: Starting applications with PM2...${NC}"
cd "$DEPLOY_DIR"
pm2 delete all 2>/dev/null || true
pm2 start ecosystem.config.js
pm2 save
print_status "Applications started"

# Step 13: Setup PM2 startup
echo ""
echo -e "${YELLOW}Step 12: Configuring PM2 to start on boot...${NC}"
pm2 startup | tail -1 | sudo bash
print_status "PM2 startup configured"

# Step 14: Configure Apache
echo ""
echo -e "${YELLOW}Step 13: Configuring Apache web server...${NC}"
print_warning "This requires manual configuration or root access."
echo "Create Apache virtual host configuration:"
echo ""

if [ "$PKG_MANAGER" == "yum" ]; then
    CONFIG_PATH="/etc/httpd/conf.d/$DOMAIN.conf"
else
    CONFIG_PATH="/etc/apache2/sites-available/$DOMAIN.conf"
fi

echo "sudo nano $CONFIG_PATH"
echo ""
echo "Add the following configuration:"
cat << 'EOF'

<VirtualHost *:80>
    ServerName chasedaddy.ai
    ServerAlias www.chasedaddy.ai

    ProxyPreserveHost On
    ProxyPass / http://localhost:3001/
    ProxyPassReverse / http://localhost:3001/

    RewriteEngine on
    RewriteCond %{HTTP:Upgrade} websocket [NC]
    RewriteCond %{HTTP:Connection} upgrade [NC]
    RewriteRule ^/?(.*) "ws://localhost:3001/$1" [P,L]

    ErrorLog /var/log/httpd/chasedaddy.ai-error.log
    CustomLog /var/log/httpd/chasedaddy.ai-access.log combined
</VirtualHost>

EOF

echo ""
read -p "Would you like to create this Apache config automatically? (requires sudo) [y/N]: " create_apache

if [[ "$create_apache" =~ ^[Yy]$ ]]; then
    sudo tee "$CONFIG_PATH" > /dev/null << 'APACHEEOF'
<VirtualHost *:80>
    ServerName chasedaddy.ai
    ServerAlias www.chasedaddy.ai

    ProxyPreserveHost On
    ProxyPass / http://localhost:3001/
    ProxyPassReverse / http://localhost:3001/

    RewriteEngine on
    RewriteCond %{HTTP:Upgrade} websocket [NC]
    RewriteCond %{HTTP:Connection} upgrade [NC]
    RewriteRule ^/?(.*) "ws://localhost:3001/$1" [P,L]

    ErrorLog /var/log/httpd/chasedaddy.ai-error.log
    CustomLog /var/log/httpd/chasedaddy.ai-access.log combined
</VirtualHost>
APACHEEOF

    # Enable required modules
    if [ "$WEB_SERVER" == "apache2" ]; then
        sudo a2enmod proxy proxy_http ssl rewrite headers
        sudo a2ensite "$DOMAIN.conf"
        sudo systemctl restart apache2
    else
        sudo systemctl restart httpd
    fi
    print_status "Apache configured and restarted"
fi

# Step 15: SSL with Let's Encrypt
echo ""
echo -e "${YELLOW}Step 14: SSL Certificate Setup${NC}"
echo "To setup SSL with Let's Encrypt, run:"
echo ""
if [ "$PKG_MANAGER" == "yum" ]; then
    echo "sudo yum install -y certbot python3-certbot-apache"
else
    echo "sudo apt install -y certbot python3-certbot-apache"
fi
echo "sudo certbot --apache -d $DOMAIN -d www.$DOMAIN"
echo ""

read -p "Would you like to install SSL certificate now? (requires sudo) [y/N]: " install_ssl

if [[ "$install_ssl" =~ ^[Yy]$ ]]; then
    if [ "$PKG_MANAGER" == "yum" ]; then
        sudo yum install -y certbot python3-certbot-apache
    else
        sudo apt install -y certbot python3-certbot-apache
    fi
    sudo certbot --apache -d "$DOMAIN" -d "www.$DOMAIN"
    print_status "SSL certificate installed"
fi

# Final status
echo ""
echo -e "${GREEN}================================${NC}"
echo -e "${GREEN}Deployment Complete!${NC}"
echo -e "${GREEN}================================${NC}"
echo ""
print_status "Application is running on http://$DOMAIN"
echo ""
echo "Useful commands:"
echo "  pm2 status          - Check application status"
echo "  pm2 logs            - View application logs"
echo "  pm2 restart all     - Restart all applications"
echo "  pm2 stop all        - Stop all applications"
echo ""
echo "Log files location: $DEPLOY_DIR/logs/"
echo ""
print_warning "Make sure your DNS is properly configured and propagated!"
print_warning "Test your site: curl http://localhost:$CLIENT_PORT"
echo ""
