#!/bin/bash
set -euo pipefail

# Ginxsom Deployment Script
# This script sets up the ginxsom blossom server configuration

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

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

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

check_root() {
    if [[ $EUID -eq 0 ]]; then
        log_error "This script should not be run as root. Please run as a regular user with sudo access."
        exit 1
    fi
}

check_dependencies() {
    log_info "Checking dependencies..."
    
    if ! command -v nginx &> /dev/null; then
        log_error "nginx is not installed. Please install nginx first."
        exit 1
    fi
    
    if ! command -v systemctl &> /dev/null; then
        log_error "systemctl is not available. This script requires systemd."
        exit 1
    fi
    
    log_info "Dependencies check passed."
}

create_directories() {
    log_info "Creating required directories..."
    
    # Create data directories
    sudo mkdir -p /var/lib/ginxsom/files
    sudo mkdir -p /var/lib/ginxsom/db
    sudo mkdir -p /run/ginxsom
    sudo mkdir -p /var/log/ginxsom
    sudo mkdir -p /etc/ginxsom
    
    log_info "Directories created."
}

create_user() {
    log_info "Creating ginxsom user..."
    
    if ! id "ginxsom" &>/dev/null; then
        sudo useradd --system --no-create-home --shell /bin/false ginxsom
        log_info "User 'ginxsom' created."
    else
        log_info "User 'ginxsom' already exists."
    fi
}

set_permissions() {
    log_info "Setting file permissions..."
    
    # Set ownership of data directories
    sudo chown -R ginxsom:ginxsom /var/lib/ginxsom
    sudo chown -R ginxsom:ginxsom /run/ginxsom
    sudo chown -R ginxsom:ginxsom /var/log/ginxsom
    sudo chown -R ginxsom:ginxsom /etc/ginxsom
    
    # Set proper permissions
    sudo chmod 755 /var/lib/ginxsom
    sudo chmod 755 /var/lib/ginxsom/files
    sudo chmod 755 /var/lib/ginxsom/db
    sudo chmod 755 /run/ginxsom
    sudo chmod 755 /var/log/ginxsom
    sudo chmod 755 /etc/ginxsom
    
    log_info "Permissions set."
}

deploy_nginx_config() {
    log_info "Deploying nginx configuration..."
    
    # Copy nginx configuration
    sudo cp "$SCRIPT_DIR/nginx/ginxsom.conf" /etc/nginx/sites-available/ginxsom
    
    # Enable the site
    if [[ ! -L /etc/nginx/sites-enabled/ginxsom ]]; then
        sudo ln -sf /etc/nginx/sites-available/ginxsom /etc/nginx/sites-enabled/ginxsom
        log_info "Nginx site enabled."
    else
        log_info "Nginx site already enabled."
    fi
    
    # Test nginx configuration
    if sudo nginx -t; then
        log_info "Nginx configuration test passed."
    else
        log_error "Nginx configuration test failed. Please check the configuration."
        exit 1
    fi
}

deploy_systemd_service() {
    log_info "Deploying systemd service..."
    
    # Copy systemd service file
    sudo cp "$SCRIPT_DIR/systemd/ginxsom.service" /etc/systemd/system/ginxsom.service
    
    # Reload systemd
    sudo systemctl daemon-reload
    
    log_info "Systemd service installed."
}

create_sample_config() {
    log_info "Creating sample configuration..."
    
    if [[ ! -f /etc/ginxsom/config.toml ]]; then
        sudo tee /etc/ginxsom/config.toml > /dev/null << 'EOF'
# Ginxsom Blossom Server Configuration

[server]
# FastCGI socket path
socket = "/run/ginxsom/ginxsom.sock"

# Data directory for files
data_dir = "/var/lib/ginxsom"

# Maximum file size in bytes (100MB)
max_file_size = 104857600

[logging]
level = "info"
file = "/var/log/ginxsom/ginxsom.log"

[storage]
# File storage directory
files_dir = "/var/lib/ginxsom/files"

# Database file for metadata
database = "/var/lib/ginxsom/db/ginxsom.db"

[auth]
# Enable authentication for uploads
require_auth = true

# Enable list endpoint
enable_list = false

# Enable mirror endpoint
enable_mirror = false
EOF
        sudo chown ginxsom:ginxsom /etc/ginxsom/config.toml
        sudo chmod 640 /etc/ginxsom/config.toml
        log_info "Sample configuration created at /etc/ginxsom/config.toml"
    else
        log_info "Configuration file already exists at /etc/ginxsom/config.toml"
    fi
}

show_status() {
    log_info "Deployment complete! Next steps:"
    echo ""
    echo "1. Build and install the ginxsom binary:"
    echo "   cd $PROJECT_ROOT"
    echo "   make build"
    echo "   sudo make install"
    echo ""
    echo "2. Start the services:"
    echo "   sudo systemctl enable ginxsom"
    echo "   sudo systemctl start ginxsom"
    echo "   sudo systemctl reload nginx"
    echo ""
    echo "3. Check status:"
    echo "   sudo systemctl status ginxsom"
    echo "   sudo systemctl status nginx"
    echo ""
    echo "4. Test the server:"
    echo "   curl http://localhost/health"
    echo ""
    echo "Configuration files:"
    echo "   - Nginx: /etc/nginx/sites-available/ginxsom"
    echo "   - SystemD: /etc/systemd/system/ginxsom.service"
    echo "   - Config: /etc/ginxsom/config.toml"
    echo ""
}

main() {
    log_info "Starting ginxsom deployment..."
    
    check_root
    check_dependencies
    create_user
    create_directories
    set_permissions
    deploy_nginx_config
    deploy_systemd_service
    create_sample_config
    show_status
    
    log_info "Deployment script completed successfully!"
}

# Parse command line arguments
case "${1:-}" in
    --help|-h)
        echo "Usage: $0 [options]"
        echo ""
        echo "Options:"
        echo "  --help, -h    Show this help message"
        echo ""
        echo "This script deploys the ginxsom blossom server configuration."
        exit 0
        ;;
    *)
        main "$@"
        ;;
esac
