#!/bin/bash
set -e

# YarnAI VPS Deployment Script
# Run as root or with sudo

DOMAIN="${DOMAIN:-yarnai.app}"
APP_DIR="/var/www/yarnai"
LOG_DIR="/var/log/yarnai"
DEPLOY_USER="yarnai"

echo "=========================================="
echo "YarnAI VPS Deployment"
echo "Domain: $DOMAIN"
echo "=========================================="

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

print_status() { echo -e "${GREEN}[OK]${NC} $1"; }
print_warning() { echo -e "${YELLOW}[WARN]${NC} $1"; }
print_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    print_error "Please run as root (sudo ./deploy.sh)"
    exit 1
fi

echo ""
echo ">>> Step 1: System Updates"
apt-get update && apt-get upgrade -y
print_status "System updated"

echo ""
echo ">>> Step 2: Install Dependencies"
apt-get install -y curl git nginx certbot python3-certbot-nginx ufw
print_status "Base dependencies installed"

# Install Node.js 20 LTS
if ! command -v node &> /dev/null; then
    curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
    apt-get install -y nodejs
    print_status "Node.js installed: $(node -v)"
else
    print_status "Node.js already installed: $(node -v)"
fi

# Install PM2
if ! command -v pm2 &> /dev/null; then
    npm install -g pm2
    print_status "PM2 installed"
else
    print_status "PM2 already installed"
fi

echo ""
echo ">>> Step 3: Create Application User"
if ! id "$DEPLOY_USER" &>/dev/null; then
    useradd -m -s /bin/bash $DEPLOY_USER
    print_status "User $DEPLOY_USER created"
else
    print_status "User $DEPLOY_USER already exists"
fi

echo ""
echo ">>> Step 4: Create Directories"
mkdir -p $APP_DIR
mkdir -p $LOG_DIR
mkdir -p /var/www/certbot
chown -R $DEPLOY_USER:$DEPLOY_USER $APP_DIR
chown -R $DEPLOY_USER:$DEPLOY_USER $LOG_DIR
print_status "Directories created"

echo ""
echo ">>> Step 5: Copy Application Files"
if [ -d "./dist" ]; then
    cp -r ./dist $APP_DIR/
    cp -r ./node_modules $APP_DIR/ 2>/dev/null || true
    cp ./package.json $APP_DIR/
    cp ./package-lock.json $APP_DIR/ 2>/dev/null || true
    cp ./ecosystem.config.cjs $APP_DIR/
    cp ./.env $APP_DIR/ 2>/dev/null || print_warning ".env not found - copy manually"
    chown -R $DEPLOY_USER:$DEPLOY_USER $APP_DIR
    print_status "Application files copied"
else
    print_error "No dist folder found. Run 'npm run build' first"
    exit 1
fi

echo ""
echo ">>> Step 6: Install Production Dependencies"
cd $APP_DIR
if ! sudo -u $DEPLOY_USER npm ci --only=production; then
    print_error "Failed to install dependencies"
    exit 1
fi
print_status "Dependencies installed"

echo ""
echo ">>> Step 7: Configure Nginx"
cat > /etc/nginx/sites-available/yarnai << 'NGINX_EOF'
server {
    listen 80;
    server_name DOMAIN_PLACEHOLDER www.DOMAIN_PLACEHOLDER;
    
    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }
    
    location / {
        return 301 https://$server_name$request_uri;
    }
}

server {
    listen 443 ssl http2;
    server_name DOMAIN_PLACEHOLDER www.DOMAIN_PLACEHOLDER;
    
    ssl_certificate /etc/letsencrypt/live/DOMAIN_PLACEHOLDER/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/DOMAIN_PLACEHOLDER/privkey.pem;
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers off;
    
    add_header Strict-Transport-Security "max-age=63072000" always;
    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;
    
    client_max_body_size 10M;
    
    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml;
    
    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
        proxy_read_timeout 300s;
    }
}
NGINX_EOF

sed -i "s/DOMAIN_PLACEHOLDER/$DOMAIN/g" /etc/nginx/sites-available/yarnai
ln -sf /etc/nginx/sites-available/yarnai /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default 2>/dev/null || true
print_status "Nginx configured"

echo ""
echo ">>> Step 8: Configure Firewall"
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw --force enable
print_status "Firewall configured"

echo ""
echo ">>> Step 9: SSL Certificate"
echo "Getting SSL certificate for $DOMAIN..."
# First start nginx without SSL for ACME challenge
cat > /etc/nginx/sites-available/yarnai-temp << EOF
server {
    listen 80;
    server_name $DOMAIN www.$DOMAIN;
    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }
    location / {
        return 200 'OK';
    }
}
EOF
ln -sf /etc/nginx/sites-available/yarnai-temp /etc/nginx/sites-enabled/yarnai
nginx -t && systemctl restart nginx

certbot certonly --webroot -w /var/www/certbot -d $DOMAIN -d www.$DOMAIN --non-interactive --agree-tos --email admin@$DOMAIN || print_warning "SSL setup failed - run manually"

# Restore full config
ln -sf /etc/nginx/sites-available/yarnai /etc/nginx/sites-enabled/yarnai
rm /etc/nginx/sites-available/yarnai-temp
nginx -t && systemctl restart nginx
print_status "SSL configured"

echo ""
echo ">>> Step 10: Start Application with PM2"
cd $APP_DIR
sudo -u $DEPLOY_USER pm2 delete yarnai 2>/dev/null || true
sudo -u $DEPLOY_USER pm2 start ecosystem.config.cjs --env production
sudo -u $DEPLOY_USER pm2 save
sudo -u $DEPLOY_USER pm2 startup systemd -u $DEPLOY_USER --hp /home/$DEPLOY_USER
print_status "Application started"

echo ""
echo ">>> Step 11: Setup Auto-renewal for SSL"
(crontab -l 2>/dev/null; echo "0 3 * * * certbot renew --quiet --post-hook 'systemctl reload nginx'") | crontab -
print_status "SSL auto-renewal configured"

echo ""
echo "=========================================="
echo -e "${GREEN}DEPLOYMENT COMPLETE!${NC}"
echo "=========================================="
echo ""
echo "Your app should now be running at: https://$DOMAIN"
echo ""
echo "Useful commands:"
echo "  pm2 status          - Check app status"
echo "  pm2 logs yarnai     - View logs"
echo "  pm2 restart yarnai  - Restart app"
echo "  pm2 monit           - Monitor dashboard"
echo ""
echo "Next steps:"
echo "  1. Point your domain DNS to this server's IP"
echo "  2. Copy .env file with real API keys to $APP_DIR/.env"
echo "  3. Run: pm2 restart yarnai"
echo ""
