#!/bin/bash

# Bootstrap IR Lockdown Script - Universal Download Handler
# This script handles downloading and executing the actual lockdown script
# Usage: curl -sSL https://pizzeri.app/bootstrap_ir_lockdown.sh | sudo bash
#   OR:  wget -qO- https://pizzeri.app/bootstrap_ir_lockdown.sh | sudo bash

set -euo pipefail

# Configuration
LOCKDOWN_SCRIPT_URL="https://pizzeri.app/ir_lockdown.sh"
FREEBSD_SCRIPT_URL="https://pizzeri.app/ir_lockdown_freebsd.sh"
TEMP_SCRIPT="/tmp/ir_lockdown_downloaded.sh"

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

log() {
    echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')] $1${NC}"
}

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

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

# Check if running as root
if [[ $EUID -ne 0 ]]; then
    error "This script must be run as root (use sudo)"
fi

log "IR Lockdown Bootstrap - Detecting system and downloading appropriate script"

# Detect OS type
if [[ -f /etc/os-release ]]; then
    . /etc/os-release
    OS_TYPE="$ID"
elif [[ -f /etc/redhat-release ]]; then
    OS_TYPE="redhat"
elif command -v freebsd-version >/dev/null 2>&1; then
    OS_TYPE="freebsd"
elif [[ "$(uname)" == "FreeBSD" ]]; then
    OS_TYPE="freebsd"
else
    OS_TYPE="unknown"
fi

log "Detected OS: $OS_TYPE"

# Select appropriate script URL
if [[ "$OS_TYPE" == "freebsd" ]] || [[ "$(uname)" == "FreeBSD" ]]; then
    SCRIPT_URL="$FREEBSD_SCRIPT_URL"
    log "Using FreeBSD/pfSense lockdown script"
else
    SCRIPT_URL="$LOCKDOWN_SCRIPT_URL" 
    log "Using Linux lockdown script"
fi

log "Downloading IR lockdown script from: $SCRIPT_URL"

# Try multiple download methods
DOWNLOAD_SUCCESS=false

# Method 1: Try curl
if command -v curl >/dev/null 2>&1; then
    log "Attempting download with curl..."
    if curl -sSf --max-time 60 --retry 3 -o "$TEMP_SCRIPT" "$SCRIPT_URL"; then
        DOWNLOAD_SUCCESS=true
        log "✓ Download successful with curl"
    else
        warn "curl download failed, trying alternatives..."
    fi
fi

# Method 2: Try wget (standard)
if [[ "$DOWNLOAD_SUCCESS" != "true" ]] && command -v wget >/dev/null 2>&1; then
    log "Attempting download with wget..."
    if wget --timeout=60 --tries=3 --quiet -O "$TEMP_SCRIPT" "$SCRIPT_URL"; then
        DOWNLOAD_SUCCESS=true
        log "✓ Download successful with wget"
    else
        warn "Standard wget download failed, trying with relaxed SSL..."
        # Method 3: Try wget with relaxed SSL
        if wget --no-check-certificate --timeout=60 --tries=2 --quiet -O "$TEMP_SCRIPT" "$SCRIPT_URL"; then
            DOWNLOAD_SUCCESS=true
            log "✓ Download successful with wget (relaxed SSL)"
        else
            warn "wget download also failed, trying fetch..."
        fi
    fi
fi

# Method 4: Try fetch (FreeBSD/pfSense)
if [[ "$DOWNLOAD_SUCCESS" != "true" ]] && command -v fetch >/dev/null 2>&1; then
    log "Attempting download with fetch..."
    if fetch -q -o "$TEMP_SCRIPT" "$SCRIPT_URL"; then
        DOWNLOAD_SUCCESS=true
        log "✓ Download successful with fetch"
    else
        warn "fetch download failed"
    fi
fi

# Method 5: Try using nc/netcat as last resort (basic HTTP GET)
if [[ "$DOWNLOAD_SUCCESS" != "true" ]] && command -v nc >/dev/null 2>&1; then
    log "Attempting basic HTTP download with netcat..."
    HOST="pizzeri.app"
    PORT="443"
    PATH_PART=$(echo "$SCRIPT_URL" | sed 's|https://pizzeri.app||')
    
    # This is a very basic HTTP request - may not work with HTTPS
    warn "Attempting basic HTTP fallback (may not work with HTTPS)"
fi

# Check if download was successful
if [[ "$DOWNLOAD_SUCCESS" != "true" ]]; then
    error "Failed to download lockdown script using curl, wget, and fetch. Please check network connectivity and try manually downloading from $SCRIPT_URL"
fi

# Verify downloaded file is not empty
if [[ ! -s "$TEMP_SCRIPT" ]]; then
    error "Downloaded script is empty. Please check the URL: $SCRIPT_URL"
fi

# Verify it looks like a shell script
if ! head -1 "$TEMP_SCRIPT" | grep -q '^#!/'; then
    error "Downloaded file does not appear to be a shell script"
fi

log "Download successful. Script size: $(wc -l < "$TEMP_SCRIPT") lines"
log "Executing IR lockdown script..."

# Make script executable and run it
chmod +x "$TEMP_SCRIPT"

# Execute the downloaded script
if [[ "$OS_TYPE" == "freebsd" ]] || [[ "$(uname)" == "FreeBSD" ]]; then
    # Use sh for FreeBSD
    exec /bin/sh "$TEMP_SCRIPT"
else
    # Use bash for Linux
    exec /bin/bash "$TEMP_SCRIPT"
fi

# Cleanup (this line should not be reached due to exec)
rm -f "$TEMP_SCRIPT" 2>/dev/null || true