#!/bin/bash

# C Nostr Relay - Simple VPS Deployment Script
# Deploys the relay with event-based configuration on Ubuntu/Debian VPS

set -e

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

# Configuration
RELAY_USER="c-relay"
INSTALL_DIR="/opt/c-relay"
SERVICE_NAME="c-relay"
RELAY_PORT="8888"

# Functions
print_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

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

check_root() {
    if [[ $EUID -ne 0 ]]; then
        print_error "This script must be run as root (use sudo)"
        exit 1
    fi
}

detect_os() {
    if [[ -f /etc/debian_version ]]; then
        OS="debian"
        print_success "Detected Debian/Ubuntu system"
    elif [[ -f /etc/redhat-release ]]; then
        OS="redhat"
        print_success "Detected RedHat/CentOS system"
    else
        print_error "Unsupported operating system"
        exit 1
    fi
}

install_dependencies() {
    print_step "Installing system dependencies..."
    
    if [[ $OS == "debian" ]]; then
        apt update
        apt install -y build-essential git sqlite3 libsqlite3-dev \
            libwebsockets-dev libssl-dev libsecp256k1-dev \
            libcurl4-openssl-dev zlib1g-dev systemd curl wget
    elif [[ $OS == "redhat" ]]; then
        yum groupinstall -y "Development Tools"
        yum install -y git sqlite-devel libwebsockets-devel \
            openssl-devel libsecp256k1-devel libcurl-devel \
            zlib-devel systemd curl wget
    fi
    
    print_success "Dependencies installed"
}

create_user() {
    print_step "Creating system user for relay..."
    
    if id "$RELAY_USER" &>/dev/null; then
        print_warning "User $RELAY_USER already exists"
    else
        useradd --system --home-dir "$INSTALL_DIR" --shell /bin/false "$RELAY_USER"
        print_success "Created user: $RELAY_USER"
    fi
}

setup_directories() {
    print_step "Setting up directories..."
    
    mkdir -p "$INSTALL_DIR"
    chown "$RELAY_USER:$RELAY_USER" "$INSTALL_DIR"
    chmod 755 "$INSTALL_DIR"
    
    print_success "Directories configured"
}

build_relay() {
    print_step "Building C Nostr Relay..."
    
    # Check if we're in the source directory
    if [[ ! -f "Makefile" ]]; then
        print_error "Makefile not found. Please run this script from the c-relay source directory."
        exit 1
    fi
    
    # Clean and build
    make clean
    make
    
    if [[ ! -f "build/c_relay_x86" ]]; then
        print_error "Build failed - binary not found"
        exit 1
    fi
    
    print_success "Relay built successfully"
}

install_binary() {
    print_step "Installing relay binary..."
    
    cp build/c_relay_x86 "$INSTALL_DIR/"
    chown "$RELAY_USER:$RELAY_USER" "$INSTALL_DIR/c_relay_x86"
    chmod +x "$INSTALL_DIR/c_relay_x86"
    
    print_success "Binary installed to $INSTALL_DIR"
}

install_service() {
    print_step "Installing systemd service..."
    
    # Use the existing systemd service file
    if [[ -f "systemd/c-relay.service" ]]; then
        cp systemd/c-relay.service /etc/systemd/system/
        systemctl daemon-reload
        print_success "Systemd service installed"
    else
        print_warning "Systemd service file not found, creating basic one..."
        
        cat > /etc/systemd/system/c-relay.service << EOF
[Unit]
Description=C Nostr Relay
After=network.target

[Service]
Type=simple
User=$RELAY_USER
Group=$RELAY_USER
WorkingDirectory=$INSTALL_DIR
ExecStart=$INSTALL_DIR/c_relay_x86
Restart=always
RestartSec=5

# Security hardening
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=$INSTALL_DIR

[Install]
WantedBy=multi-user.target
EOF
        systemctl daemon-reload
        print_success "Basic systemd service created"
    fi
}

configure_firewall() {
    print_step "Configuring firewall..."
    
    if command -v ufw &> /dev/null; then
        # UFW (Ubuntu)
        ufw allow "$RELAY_PORT/tcp" comment "Nostr Relay"
        print_success "UFW rule added for port $RELAY_PORT"
    elif command -v firewall-cmd &> /dev/null; then
        # Firewalld (CentOS/RHEL)
        firewall-cmd --permanent --add-port="$RELAY_PORT/tcp"
        firewall-cmd --reload
        print_success "Firewalld rule added for port $RELAY_PORT"
    else
        print_warning "No recognized firewall found. Please manually open port $RELAY_PORT"
    fi
}

start_service() {
    print_step "Starting relay service..."
    
    systemctl enable "$SERVICE_NAME"
    systemctl start "$SERVICE_NAME"
    
    sleep 3
    
    if systemctl is-active --quiet "$SERVICE_NAME"; then
        print_success "Relay service started and enabled"
    else
        print_error "Failed to start relay service"
        print_error "Check logs with: journalctl -u $SERVICE_NAME --no-pager"
        exit 1
    fi
}

capture_admin_keys() {
    print_step "Capturing admin keys..."
    
    echo
    echo "=================================="
    echo "🔑 CRITICAL: ADMIN PRIVATE KEY 🔑"
    echo "=================================="
    echo
    print_warning "The admin private key will be shown in the service logs."
    print_warning "This key is generated ONCE and is needed for all configuration updates!"
    echo
    echo "To view the admin key, run:"
    echo "  sudo journalctl -u $SERVICE_NAME --no-pager | grep -A 5 'Admin Private Key'"
    echo
    echo "Or check recent logs:"
    echo "  sudo journalctl -u $SERVICE_NAME --since '5 minutes ago'"
    echo
    print_error "IMPORTANT: Save this key in a secure location immediately!"
    echo
}

show_status() {
    print_step "Deployment Status"
    
    echo
    echo "🎉 Deployment Complete!"
    echo
    echo "Service Status:"
    systemctl status "$SERVICE_NAME" --no-pager -l
    echo
    echo "Quick Commands:"
    echo "  Check status:  sudo systemctl status $SERVICE_NAME"
    echo "  View logs:     sudo journalctl -u $SERVICE_NAME -f"
    echo "  Restart:       sudo systemctl restart $SERVICE_NAME"
    echo "  Stop:          sudo systemctl stop $SERVICE_NAME"
    echo
    echo "Relay Information:"
    echo "  Port:          $RELAY_PORT"
    echo "  Directory:     $INSTALL_DIR"
    echo "  User:          $RELAY_USER"
    echo "  Database:      Auto-generated in $INSTALL_DIR"
    echo
    echo "Next Steps:"
    echo "1. Get your admin private key from the logs (see above)"
    echo "2. Configure your relay using the event-based system"
    echo "3. Set up SSL/TLS with a reverse proxy (nginx/apache)"
    echo "4. Configure monitoring and backups"
    echo
    echo "Documentation:"
    echo "  User Guide:      docs/user_guide.md"
    echo "  Config Guide:    docs/configuration_guide.md"
    echo "  Deployment:      docs/deployment_guide.md"
    echo
}

# Main deployment flow
main() {
    echo
    echo "=========================================="
    echo "🚀 C Nostr Relay - Simple VPS Deployment"
    echo "=========================================="
    echo
    
    check_root
    detect_os
    install_dependencies
    create_user
    setup_directories
    build_relay
    install_binary
    install_service
    configure_firewall
    start_service
    capture_admin_keys
    show_status
    
    print_success "Deployment completed successfully!"
}

# Run main function
main "$@"