#!/bin/bash

# AHA Training Website - Deployment Script
# This script sets up the website on your Debian server

echo "=============================================="
echo "  AHA Training Website - Deployment Script"
echo "=============================================="
echo ""

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

# Configuration
INSTALL_DIR="/var/www/aha-training"
DOMAIN="aha.adampowell.pro"
ADMIN_EMAIL="t3h28@gmail.com"

echo -e "${YELLOW}This script will:${NC}"
echo "  1. Set up directory permissions"
echo "  2. Initialize the database"
echo "  3. Configure Nginx (if applicable)"
echo "  4. Set up SSL certificate"
echo "  5. Test the installation"
echo ""
read -p "Continue? (y/n) " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Deployment cancelled."
    exit 1
fi

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}Error: This script must be run as root${NC}"
    exit 1
fi

echo ""
echo "=============================================="
echo "Step 1: Setting Directory Permissions"
echo "=============================================="

# Set directory permissions
chmod 755 "$INSTALL_DIR/public" "$INSTALL_DIR/app" "$INSTALL_DIR/assets"
chmod 700 "$INSTALL_DIR/private"
chmod 755 "$INSTALL_DIR/private/nda_records"

# Set file permissions
find "$INSTALL_DIR/public" -type f -exec chmod 644 {} \;
find "$INSTALL_DIR/app" -type f -exec chmod 644 {} \;
find "$INSTALL_DIR/assets" -type f -exec chmod 644 {} \;

# Make processing scripts executable
chmod 755 "$INSTALL_DIR/app/process-nda.php" "$INSTALL_DIR/app/process-contact.php"

# Secure .htaccess files
chmod 644 "$INSTALL_DIR/.htaccess" "$INSTALL_DIR/app/.htaccess" "$INSTALL_DIR/private/.htaccess"

echo -e "${GREEN}✓ Permissions set${NC}"

echo ""
echo "=============================================="
echo "Step 2: Initializing Database"
echo "=============================================="

# Create database file
touch "$INSTALL_DIR/private/aha_training.db"
chmod 666 "$INSTALL_DIR/private/aha_training.db"

# Create log files
touch "$INSTALL_DIR/private/security.log"
chmod 666 "$INSTALL_DIR/private/security.log"

echo -e "${GREEN}✓ Database initialized${NC}"

echo ""
echo "=============================================="
echo "Step 3: Web Server Configuration"
echo "=============================================="

# Detect web server
if command -v nginx &> /dev/null; then
    echo "Nginx detected. Creating configuration..."

    cat > "/etc/nginx/sites-available/$DOMAIN.conf" <<EOF
server {
    listen 80;
    server_name $DOMAIN;

    # Redirect to HTTPS (will be enabled after SSL)
    # return 301 https://\$server_name\$request_uri;

    root $INSTALL_DIR/public;
    index index.php;

    # Block access to private directory
    location /private {
        deny all;
        return 403;
    }

    # Block access to app backend files except processors
    location /app {
        deny all;
    }

    location ~ ^/app/(process-nda|process-contact)\.php$ {
        fastcgi_pass unix:/run/php/php7.3-fpm.sock;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        include fastcgi_params;
    }

    # PHP handling
    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php7.3-fpm.sock;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        include fastcgi_params;
    }

    # Static files caching
    location /assets {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
}
EOF

    # Enable site
    ln -sf "/etc/nginx/sites-available/$DOMAIN.conf" "/etc/nginx/sites-enabled/$DOMAIN.conf"

    # Test configuration
    nginx -t
    if [ $? -eq 0 ]; then
        systemctl reload nginx
        echo -e "${GREEN}✓ Nginx configured and reloaded${NC}"
    else
        echo -e "${RED}✗ Nginx configuration test failed${NC}"
    fi

elif command -v apache2 &> /dev/null; then
    echo "Apache detected. Using existing .htaccess configuration..."

    # Enable required modules
    a2enmod rewrite headers expires deflate

    # Restart Apache
    systemctl restart apache2
    echo -e "${GREEN}✓ Apache modules enabled and restarted${NC}"
else
    echo -e "${YELLOW}! No web server detected. Please configure manually.${NC}"
fi

echo ""
echo "=============================================="
echo "Step 4: SSL Certificate Setup"
echo "=============================================="

if command -v certbot &> /dev/null; then
    echo "Certbot detected."
    read -p "Install SSL certificate for $DOMAIN? (y/n) " -n 1 -r
    echo ""
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        if command -v nginx &> /dev/null; then
            certbot --nginx -d "$DOMAIN" --email "$ADMIN_EMAIL" --agree-tos --non-interactive
        elif command -v apache2 &> /dev/null; then
            certbot --apache -d "$DOMAIN" --email "$ADMIN_EMAIL" --agree-tos --non-interactive
        fi
        echo -e "${GREEN}✓ SSL certificate installed${NC}"
    else
        echo "Skipping SSL setup. Run manually later: certbot --nginx -d $DOMAIN"
    fi
else
    echo -e "${YELLOW}! Certbot not found. Install SSL manually:${NC}"
    echo "  apt install certbot python3-certbot-nginx"
    echo "  certbot --nginx -d $DOMAIN"
fi

echo ""
echo "=============================================="
echo "Step 5: Testing Installation"
echo "=============================================="

# Test database
echo -n "Testing database... "
if sqlite3 "$INSTALL_DIR/private/aha_training.db" "SELECT 1;" &> /dev/null; then
    echo -e "${GREEN}✓${NC}"
else
    echo -e "${RED}✗${NC}"
fi

# Test PHP
echo -n "Testing PHP... "
if php -v &> /dev/null; then
    echo -e "${GREEN}✓${NC}"
else
    echo -e "${RED}✗${NC}"
fi

# Test SQLite extension
echo -n "Testing SQLite extension... "
if php -m | grep -q sqlite3; then
    echo -e "${GREEN}✓${NC}"
else
    echo -e "${RED}✗ SQLite3 extension not found${NC}"
    echo "  Install: apt install php-sqlite3"
fi

# Test web server
echo -n "Testing web server... "
if systemctl is-active --quiet nginx || systemctl is-active --quiet apache2; then
    echo -e "${GREEN}✓${NC}"
else
    echo -e "${RED}✗ Web server not running${NC}"
fi

echo ""
echo "=============================================="
echo "Installation Complete!"
echo "=============================================="
echo ""
echo -e "${GREEN}✓ AHA Training website deployed successfully${NC}"
echo ""
echo "Next steps:"
echo "  1. Visit: http://$DOMAIN/public/"
echo "  2. Test NDA signing process"
echo "  3. Verify email notifications"
echo "  4. Set up automated backups"
echo ""
echo "Useful commands:"
echo "  - View database: sqlite3 $INSTALL_DIR/private/aha_training.db"
echo "  - Check logs: tail -f $INSTALL_DIR/private/security.log"
echo "  - Restart web server: systemctl restart nginx|apache2"
echo ""
echo -e "${YELLOW}Important:${NC} Review the README.md file for detailed configuration options."
echo ""
