#!/bin/bash

# PostgreSQL Ubuntu Server Setup Script for Church Song Lyric System
# Configured for PostgreSQL on port 5100

set -e

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

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

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 configuration
echo -e "${YELLOW}Please provide the following information:${NC}"
read -p "Enter your server IP [192.168.10.130]: " SERVER_IP
SERVER_IP=${SERVER_IP:-192.168.10.130}

read -p "Enter PostgreSQL password for songlyric_user: " -s DB_PASSWORD
echo ""

read -p "Enter the installation directory [/var/www/church-songlyric]: " INSTALL_DIR
INSTALL_DIR=${INSTALL_DIR:-/var/www/church-songlyric}

echo ""
echo -e "${GREEN}Server IP: $SERVER_IP${NC}"
echo -e "${GREEN}Installation directory: $INSTALL_DIR${NC}"
echo ""

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

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

echo ""
echo "Step 2: Installing PostgreSQL..."
sudo apt install -y postgresql postgresql-contrib libpq-dev

sudo systemctl start postgresql
sudo systemctl enable postgresql

echo ""
echo "Step 3: Creating PostgreSQL database and user..."

sudo -u postgres psql <<EOF
CREATE DATABASE church_songlyric;
CREATE USER songlyric_user WITH ENCRYPTED PASSWORD '$DB_PASSWORD';
GRANT ALL PRIVILEGES ON DATABASE church_songlyric TO songlyric_user;
\c church_songlyric
GRANT ALL ON SCHEMA public TO songlyric_user;
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO songlyric_user;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO songlyric_user;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO songlyric_user;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO songlyric_user;
EOF

echo ""
echo "Step 4: Configuring PostgreSQL for network access..."

PG_VERSION=$(ls /etc/postgresql/ | head -n 1)
PG_CONF="/etc/postgresql/$PG_VERSION/main/postgresql.conf"
PG_HBA="/etc/postgresql/$PG_VERSION/main/pg_hba.conf"

sudo sed -i "s/#listen_addresses = 'localhost'/listen_addresses = '*'/" "$PG_CONF"
echo "host    church_songlyric    songlyric_user    192.168.10.0/24    md5" | sudo tee -a "$PG_HBA"

sudo systemctl restart postgresql

echo ""
echo "Step 5: Installing system packages..."
sudo apt install -y \
    python3 \
    python3-pip \
    python3-venv \
    python3-dev \
    nodejs \
    npm \
    nginx \
    git \
    curl \
    ufw \
    tesseract-ocr \
    poppler-utils \
    libtesseract-dev \
    libleptonica-dev

echo ""
echo "Step 6: Configuring firewall..."
sudo ufw --force enable
sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw allow 5432/tcp
sudo ufw status

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

cd "$INSTALL_DIR"

if [ ! -d "backend" ]; then
    echo -e "${YELLOW}Backend directory not found.${NC}"
    echo -e "${YELLOW}Please transfer your project files to $INSTALL_DIR${NC}"
    read -p "Press Enter when files are transferred..."
fi

if [ -d "backend" ]; then
    cd backend
    
    echo "Creating Python virtual environment..."
    python3 -m venv venv
    
    echo "Installing Python dependencies..."
    source venv/bin/activate
    pip install --upgrade pip
    
    if [ -f "requirements.txt" ]; then
        pip install -r requirements.txt
    fi
    
    # Create .env file
    cat > .env <<ENV_EOF
# PostgreSQL connection
POSTGRESQL_URI=postgresql://songlyric_user:$DB_PASSWORD@$SERVER_IP:5432/church_songlyric

# Flask configuration
FLASK_PORT=5100
FLASK_ENV=production
SECRET_KEY=$(openssl rand -base64 32)

# Allowed origins
ALLOWED_ORIGINS=http://$SERVER_IP,http://192.168.10.178:3000
ENV_EOF

    echo "Migrating data to PostgreSQL..."
    python migrate_to_postgresql.py || echo "Migration skipped or failed"
    
    deactivate
    cd ..
fi

echo ""
echo "Step 8: Setting up frontend..."
if [ -d "frontend" ]; then
    cd frontend
    
    npm install
    
    cat > .env.production <<FRONTEND_ENV
REACT_APP_API_URL=http://$SERVER_IP/api
GENERATE_SOURCEMAP=false
FRONTEND_ENV

    npm run build
    cd ..
fi

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

[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
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

echo ""
echo "Step 10: Configuring Nginx..."
sudo tee /etc/nginx/sites-available/church-songlyric > /dev/null <<EOF
server {
    listen 80;
    server_name $SERVER_IP;

    root $INSTALL_DIR/frontend/build;
    index index.html;

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

    location /api {
        proxy_pass http://localhost:5100;
        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;
        proxy_connect_timeout 600;
        proxy_send_timeout 600;
        proxy_read_timeout 600;
        send_timeout 600;
    }

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

    client_max_body_size 50M;
}
EOF

sudo ln -sf /etc/nginx/sites-available/church-songlyric /etc/nginx/sites-enabled/
sudo rm -f /etc/nginx/sites-enabled/default
sudo nginx -t

echo ""
echo "Step 11: Setting permissions..."
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}Starting services...${NC}"
sudo systemctl daemon-reload
sudo systemctl enable church-songlyric-backend
sudo systemctl start church-songlyric-backend
sudo systemctl restart nginx

echo ""
echo -e "${GREEN}Service Status:${NC}"
sudo systemctl status church-songlyric-backend --no-pager
echo ""

echo -e "${GREEN}Access your application at: http://$SERVER_IP${NC}"
echo ""
echo "Management commands:"
echo "  sudo systemctl status church-songlyric-backend"
echo "  sudo systemctl restart church-songlyric-backend"
echo "  sudo journalctl -u church-songlyric-backend -f"
echo ""
