#!/bin/bash

###############################################################################
# LuckyChit Automated Deployment Script for Proxmox LXC
# Author: LuckyChit Team
# Description: Automates the deployment of LuckyChit app on Ubuntu LXC
###############################################################################

set -e  # Exit on error

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

# Functions
print_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

print_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

print_error() {
    echo -e "${RED}❌ $1${NC}"
}

print_header() {
    echo ""
    echo -e "${GREEN}╔════════════════════════════════════════════════════════╗${NC}"
    echo -e "${GREEN}║     LuckyChit Deployment Script for Proxmox LXC       ║${NC}"
    echo -e "${GREEN}╚════════════════════════════════════════════════════════╝${NC}"
    echo ""
}

check_root() {
    if [ "$EUID" -ne 0 ]; then
        print_error "Please run as root or with sudo"
        exit 1
    fi
}

###############################################################################
# Main Installation
###############################################################################

print_header

# Check if running as root
check_root

# Get configuration from user
print_info "Starting interactive setup..."
echo ""

read -p "Enter database password for PostgreSQL: " DB_PASSWORD
read -p "Enter JWT secret (min 32 characters): " JWT_SECRET
read -p "Enter your domain name (or press Enter to skip): " DOMAIN_NAME
read -p "Enter your server IP address: " SERVER_IP

echo ""
print_info "Configuration received. Starting installation..."
echo ""

###############################################################################
# 1. System Update
###############################################################################
print_info "Step 1/10: Updating system..."
apt update && apt upgrade -y
apt install -y curl wget git nano ufw htop postgresql postgresql-contrib nginx
print_success "System updated"

###############################################################################
# 2. Create Application User
###############################################################################
print_info "Step 2/10: Creating application user..."
if id "luckychit" &>/dev/null; then
    print_warning "User 'luckychit' already exists"
else
    adduser --disabled-password --gecos "" luckychit
    usermod -aG sudo luckychit
    print_success "User 'luckychit' created"
fi

###############################################################################
# 3. Install Node.js
###############################################################################
print_info "Step 3/10: Installing Node.js v20..."
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt install -y nodejs
print_success "Node.js $(node --version) installed"

###############################################################################
# 4. Install PM2
###############################################################################
print_info "Step 4/10: Installing PM2..."
npm install -g pm2
print_success "PM2 installed"

###############################################################################
# 5. Setup PostgreSQL
###############################################################################
print_info "Step 5/10: Configuring PostgreSQL..."
systemctl start postgresql
systemctl enable postgresql

sudo -u postgres psql << EOF
CREATE DATABASE luckychit;
CREATE USER luckychit WITH PASSWORD '$DB_PASSWORD';
GRANT ALL PRIVILEGES ON DATABASE luckychit TO luckychit;
EOF

print_success "PostgreSQL configured"

###############################################################################
# 6. Install Flutter
###############################################################################
print_info "Step 6/10: Installing Flutter..."
apt install -y clang cmake ninja-build pkg-config libgtk-3-dev unzip

if [ ! -d "/opt/flutter" ]; then
    cd /opt
    git clone https://github.com/flutter/flutter.git -b stable
    chown -R luckychit:luckychit /opt/flutter
    print_success "Flutter installed"
else
    print_warning "Flutter already installed"
fi

# Add Flutter to PATH for all users
if ! grep -q "flutter/bin" /etc/profile.d/flutter.sh 2>/dev/null; then
    echo 'export PATH="$PATH:/opt/flutter/bin"' > /etc/profile.d/flutter.sh
    chmod +x /etc/profile.d/flutter.sh
fi

export PATH="$PATH:/opt/flutter/bin"
flutter config --enable-web

print_success "Flutter configured for web"

###############################################################################
# 7. Create Directory Structure
###############################################################################
print_info "Step 7/10: Creating directory structure..."
mkdir -p /home/luckychit/apps
mkdir -p /home/luckychit/logs
mkdir -p /home/luckychit/backups
chown -R luckychit:luckychit /home/luckychit

print_success "Directories created"

###############################################################################
# 8. Setup Firewall
###############################################################################
print_info "Step 8/10: Configuring firewall..."
ufw --force enable
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
print_success "Firewall configured"

###############################################################################
# 9. Setup Nginx (Basic Config)
###############################################################################
print_info "Step 9/10: Configuring Nginx..."

cat > /etc/nginx/sites-available/luckychit << 'NGINX_EOF'
server {
    listen 80;
    server_name _;

    location /api/ {
        proxy_pass http://localhost:3000/api/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        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;
    }

    location /health {
        proxy_pass http://localhost:3000/health;
        access_log off;
    }

    location / {
        root /var/www/luckychit;
        index index.html;
        try_files $uri $uri/ /index.html;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
        root /var/www/luckychit;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}
NGINX_EOF

ln -sf /etc/nginx/sites-available/luckychit /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default

nginx -t && systemctl reload nginx
print_success "Nginx configured"

###############################################################################
# 10. Create .env Template
###############################################################################
print_info "Step 10/10: Creating environment file template..."

mkdir -p /home/luckychit/apps/chitfund/backend

cat > /home/luckychit/apps/chitfund/backend/.env << ENV_EOF
# Server Configuration
NODE_ENV=production
PORT=3000

# Database Configuration
DB_HOST=localhost
DB_PORT=5432
DB_NAME=luckychit
DB_USER=luckychit
DB_PASSWORD=$DB_PASSWORD
DATABASE_URL=postgresql://luckychit:$DB_PASSWORD@localhost:5432/luckychit

# JWT Configuration
JWT_SECRET=$JWT_SECRET
JWT_EXPIRES_IN=24h

# CORS Configuration
ALLOWED_ORIGINS=http://$SERVER_IP,https://$DOMAIN_NAME

# Rate Limiting
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=100

# Logging
LOG_LEVEL=info
ENV_EOF

chown luckychit:luckychit /home/luckychit/apps/chitfund/backend/.env
chmod 600 /home/luckychit/apps/chitfund/backend/.env

print_success "Environment file created"

###############################################################################
# Create Backup Script
###############################################################################
print_info "Creating backup script..."

cat > /home/luckychit/backup-db.sh << 'BACKUP_EOF'
#!/bin/bash
BACKUP_DIR="/home/luckychit/backups"
DATE=$(date +%Y%m%d_%H%M%S)
FILENAME="luckychit_backup_$DATE.sql"

pg_dump -U luckychit -h localhost luckychit > "$BACKUP_DIR/$FILENAME"
gzip "$BACKUP_DIR/$FILENAME"

# Keep only last 7 days of backups
find $BACKUP_DIR -name "luckychit_backup_*.sql.gz" -mtime +7 -delete

echo "Backup completed: $FILENAME.gz"
BACKUP_EOF

chmod +x /home/luckychit/backup-db.sh
chown luckychit:luckychit /home/luckychit/backup-db.sh

# Add to crontab for luckychit user
(crontab -u luckychit -l 2>/dev/null; echo "0 2 * * * /home/luckychit/backup-db.sh") | crontab -u luckychit -

print_success "Backup script created (runs daily at 2 AM)"

###############################################################################
# Installation Complete
###############################################################################

echo ""
echo -e "${GREEN}╔════════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║            Installation Complete! 🎉                  ║${NC}"
echo -e "${GREEN}╚════════════════════════════════════════════════════════╝${NC}"
echo ""

print_success "LuckyChit infrastructure is ready!"
echo ""
print_info "Next Steps:"
echo ""
echo "  1. Upload your application code to:"
echo "     /home/luckychit/apps/chitfund/"
echo ""
echo "  2. Deploy the backend:"
echo "     cd /home/luckychit/apps/chitfund/backend"
echo "     npm install --production"
echo "     node create-db.js"
echo "     pm2 start src/server.js --name luckychit-api"
echo "     pm2 startup systemd -u luckychit --hp /home/luckychit"
echo "     pm2 save"
echo ""
echo "  3. Build and deploy the frontend:"
echo "     cd /home/luckychit/apps/chitfund/luckychit"
echo "     flutter pub get"
echo "     flutter build web --release"
echo "     sudo cp -r build/web/* /var/www/luckychit/"
echo ""
echo "  4. Access your application:"
echo "     Frontend: http://$SERVER_IP"
echo "     API Health: http://$SERVER_IP/health"
echo ""
echo "  5. (Optional) Setup SSL:"
echo "     apt install certbot python3-certbot-nginx"
echo "     certbot --nginx -d $DOMAIN_NAME"
echo ""

print_warning "Important: Review and update the .env file at:"
print_warning "/home/luckychit/apps/chitfund/backend/.env"
echo ""

print_info "Documentation available at:"
echo "  - Full Guide: PROXMOX_DEPLOYMENT_GUIDE.md"
echo "  - Quick Reference: QUICK_DEPLOY.md"
echo ""

print_success "Deployment script completed successfully!"

