#!/bin/bash

# Ubuntu Server Setup Script for Church Song Lyric System
# This script automates the initial setup on a fresh Ubuntu server

set -e  # Exit on error

echo "=========================================="
echo "Church Song Lyric - Ubuntu Setup"
echo "=========================================="
echo ""

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

# Check if running as root
if [ "$EUID" -eq 0 ]; then 
    echo -e "${RED}Please do not run as root. Run as regular user with sudo privileges.${NC}"
    exit 1
fi

# Get user input
echo -e "${YELLOW}Please provide the following information:${NC}"
read -p "Enter your domain name (or press Enter to skip): " DOMAIN_NAME
read -p "Enter the installation directory [/var/www/church-songlyric]: " INSTALL_DIR
INSTALL_DIR=${INSTALL_DIR:-/var/www/church-songlyric}

echo ""
echo -e "${GREEN}Installation directory: $INSTALL_DIR${NC}"
if [ ! -z "$DOMAIN_NAME" ]; then
    echo -e "${GREEN}Domain name: $DOMAIN_NAME${NC}"
else
    echo -e "${YELLOW}No domain name provided. Will use IP address.${NC}"
fi
echo ""

read -p "Continue with installation? (y/n): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    exit 1
fi

echo ""
echo "=========================================="
echo "Step 1: Updating system packages..."
echo "=========================================="
sudo apt update
sudo apt upgrade -y

echo ""
echo "=========================================="
echo "Step 2: Installing required packages..."
echo "=========================================="
sudo apt install -y \
    python3 \
    python3-pip \
    python3-venv \
    nodejs \
    npm \
    nginx \
    git \
    curl \
    wget \
    ufw \
    tesseract-ocr \
    poppler-utils \
    libtesseract-dev \
    libleptonica-dev \
    software-properties-common

# Check Node.js version
NODE_VERSION=$(node -v | cut -d'v' -f2 | cut -d'.' -f1)
if [ "$NODE_VERSION" -lt 16 ]; then
    echo -e "${YELLOW}Node.js version is too old. Installing Node.js 18 LTS...${NC}"
    curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
    sudo apt install -y nodejs
fi

echo ""
echo "=========================================="
echo "Step 3: Configuring firewall..."
echo "=========================================="
sudo ufw --force enable
sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw status

echo ""
echo "=========================================="
echo "Step 4: Creating project directory..."
echo "=========================================="
sudo mkdir -p "$INSTALL_DIR"
sudo chown $USER:www-data "$INSTALL_DIR"
sudo chmod 755 "$INSTALL_DIR"

echo ""
echo "=========================================="
echo "Step 5: Setting up Python environment..."
echo "=========================================="
cd "$INSTALL_DIR"

# Check if project files exist
if [ ! -d "backend" ]; then
    echo -e "${YELLOW}Backend directory not found.${NC}"
    echo -e "${YELLOW}Please transfer your project files to $INSTALL_DIR${NC}"
    echo -e "${YELLOW}You can use: scp -r /path/to/project/* user@server:$INSTALL_DIR/${NC}"
    read -p "Press Enter when files are transferred..."
fi

if [ -d "backend" ]; then
    cd backend
    
    # Create virtual environment
    echo "Creating Python virtual environment..."
    python3 -m venv venv
    
    # Activate and install dependencies
    echo "Installing Python dependencies..."
    source venv/bin/activate
    pip install --upgrade pip
    
    if [ -f "requirements.txt" ]; then
        pip install -r requirements.txt
    else
        echo -e "${YELLOW}requirements.txt not found. Skipping Python package installation.${NC}"
    fi
    
    deactivate
    cd ..
else
    echo -e "${RED}Backend directory still not found. Skipping Python setup.${NC}"
fi

echo ""
echo "=========================================="
echo "Step 6: Setting up Node.js environment..."
echo "=========================================="
if [ -d "frontend" ]; then
    cd frontend
    
    echo "Installing Node.js dependencies..."
    npm install
    
    echo "Building production frontend..."
    npm run build
    
    cd ..
else
    echo -e "${YELLOW}Frontend directory not found. Skipping frontend setup.${NC}"
fi

echo ""
echo "=========================================="
echo "Step 7: Creating systemd service..."
echo "=========================================="
sudo tee /etc/systemd/system/church-songlyric-backend.service > /dev/null <<EOF
[Unit]
Description=Church Song Lyric Backend (Flask)
After=network.target

[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory=$INSTALL_DIR/backend
Environment="PATH=$INSTALL_DIR/backend/venv/bin"
ExecStart=$INSTALL_DIR/backend/venv/bin/python app.py
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

echo ""
echo "=========================================="
echo "Step 8: Configuring Nginx..."
echo "=========================================="

# Determine server name
if [ ! -z "$DOMAIN_NAME" ]; then
    SERVER_NAME="$DOMAIN_NAME www.$DOMAIN_NAME"
else
    SERVER_IP=$(hostname -I | awk '{print $1}')
    SERVER_NAME="$SERVER_IP"
fi

sudo tee /etc/nginx/sites-available/church-songlyric > /dev/null <<EOF
server {
    listen 80;
    server_name $SERVER_NAME;

    # Serve React frontend
    root $INSTALL_DIR/frontend/build;
    index index.html;

    # Frontend routing
    location / {
        try_files \$uri \$uri/ /index.html;
    }

    # Proxy API requests to Flask backend
    location /api {
        proxy_pass http://localhost:5000;
        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;
    }

    # Static file caching
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}
EOF

# Enable site
sudo ln -sf /etc/nginx/sites-available/church-songlyric /etc/nginx/sites-enabled/
sudo rm -f /etc/nginx/sites-enabled/default

# Test Nginx configuration
sudo nginx -t

echo ""
echo "=========================================="
echo "Step 9: Setting permissions..."
echo "=========================================="
sudo chown -R www-data:www-data "$INSTALL_DIR"
sudo chmod -R 755 "$INSTALL_DIR"

echo ""
echo "=========================================="
echo "Installation Complete!"
echo "=========================================="
echo ""
echo -e "${GREEN}Next steps:${NC}"
echo ""
echo "1. Configure your .env file:"
echo "   sudo nano $INSTALL_DIR/backend/.env"
echo ""
echo "2. Add your MongoDB connection string and other settings"
echo ""
echo "3. Start the services:"
echo "   sudo systemctl daemon-reload"
echo "   sudo systemctl enable church-songlyric-backend"
echo "   sudo systemctl start church-songlyric-backend"
echo "   sudo systemctl restart nginx"
echo ""
echo "4. Check service status:"
echo "   sudo systemctl status church-songlyric-backend"
echo "   sudo systemctl status nginx"
echo ""
echo "5. (Optional) Set up SSL certificate:"
echo "   sudo apt install certbot python3-certbot-nginx"
echo "   sudo certbot --nginx -d $DOMAIN_NAME"
echo ""
if [ ! -z "$DOMAIN_NAME" ]; then
    echo -e "${GREEN}Access your application at: http://$DOMAIN_NAME${NC}"
else
    SERVER_IP=$(hostname -I | awk '{print $1}')
    echo -e "${GREEN}Access your application at: http://$SERVER_IP${NC}"
fi
echo ""
echo "For more details, see: $INSTALL_DIR/UBUNTU_DEPLOYMENT_GUIDE.md"
echo ""
