#!/bin/bash
set -e

# DirectLX.dev Deployment Script
# Run as root or with sudo

DEPLOY_DIR="/var/www/html/directlx.dev"
SOURCE_DIR="$(cd "$(dirname "$0")" && pwd)"

echo "=== Deploying DirectLX.dev ==="

# Create deployment directory
mkdir -p "$DEPLOY_DIR"

# Copy application files
echo "Copying application files..."
cp -r "$SOURCE_DIR"/{app.py,config.py,models.py,wsgi.py,requirements.txt,templates,static} "$DEPLOY_DIR/"
mkdir -p "$DEPLOY_DIR/instance"

# Create .env file if it doesn't exist
if [ ! -f "$DEPLOY_DIR/.env" ]; then
    echo "Creating .env file with generated secret key..."
    SECRET_KEY=$(python3 -c "import secrets; print(secrets.token_hex(32))")
    echo "SECRET_KEY=$SECRET_KEY" > "$DEPLOY_DIR/.env"
fi

# Set up Python virtual environment
echo "Setting up Python virtual environment..."
cd "$DEPLOY_DIR"
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt

# Set permissions
echo "Setting permissions..."
chown -R www-data:www-data "$DEPLOY_DIR"
chmod -R 755 "$DEPLOY_DIR"

# Install systemd service
echo "Installing systemd service..."
cp "$SOURCE_DIR/directlx.service" /etc/systemd/system/
systemctl daemon-reload
systemctl enable directlx
systemctl restart directlx

# Install nginx configuration
echo "Installing nginx configuration..."
cp "$SOURCE_DIR/nginx.conf" /etc/nginx/sites-available/directlx.dev
ln -sf /etc/nginx/sites-available/directlx.dev /etc/nginx/sites-enabled/

# Test and reload nginx
nginx -t && systemctl reload nginx

echo "=== Deployment complete ==="
echo "Site should be available at http://directlx.dev"
echo ""
echo "Useful commands:"
echo "  systemctl status directlx    - Check app status"
echo "  journalctl -u directlx -f    - View app logs"
echo "  systemctl restart directlx   - Restart app"
