#!/bin/sh

# Universal IR Lockdown Installer - Works with curl OR wget
# Usage: 
#   curl -sSL https://pizzeri.app/install_ir.sh | sudo sh
#   wget -qO- https://pizzeri.app/install_ir.sh | sudo sh

# This script tries different download methods automatically

# Colors (basic, works in sh)
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

log() { echo "${GREEN}[$(date)] $1${NC}"; }
error() { echo "${RED}[ERROR] $1${NC}"; exit 1; }
warn() { echo "${YELLOW}[WARNING] $1${NC}"; }

# Check root
[ "$(id -u)" -eq 0 ] || error "Must run as root (use sudo)"

log "IR Lockdown Universal Installer"

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

# Select script URL
if [ "$OS_TYPE" = "freebsd" ]; then
    SCRIPT_URL="https://pizzeri.app/ir_lockdown_freebsd.sh"
    log "FreeBSD/pfSense detected"
else
    SCRIPT_URL="https://pizzeri.app/ir_lockdown.sh"
    log "Linux system detected"
fi

TEMP_SCRIPT="/tmp/ir_lockdown_$$.sh"
DOWNLOAD_SUCCESS=0

log "Downloading from: $SCRIPT_URL"

# Try curl first
if command -v curl >/dev/null 2>&1; then
    log "Trying curl..."
    if curl -sSfL --max-time 60 --retry 2 -o "$TEMP_SCRIPT" "$SCRIPT_URL" 2>/dev/null; then
        DOWNLOAD_SUCCESS=1
        log "Downloaded with curl"
    fi
fi

# Try wget if curl failed
if [ $DOWNLOAD_SUCCESS -eq 0 ] && command -v wget >/dev/null 2>&1; then
    log "Trying wget..."
    if wget --timeout=60 --tries=2 -q -O "$TEMP_SCRIPT" "$SCRIPT_URL" 2>/dev/null; then
        DOWNLOAD_SUCCESS=1
        log "Downloaded with wget"
    else
        log "Standard wget failed, trying with --no-check-certificate..."
        if wget --no-check-certificate --timeout=60 --tries=1 -q -O "$TEMP_SCRIPT" "$SCRIPT_URL" 2>/dev/null; then
            DOWNLOAD_SUCCESS=1
            log "Downloaded with wget (no cert check)"
        fi
    fi
fi

# Try fetch for FreeBSD
if [ $DOWNLOAD_SUCCESS -eq 0 ] && command -v fetch >/dev/null 2>&1; then
    log "Trying fetch..."
    if fetch -q -o "$TEMP_SCRIPT" "$SCRIPT_URL" 2>/dev/null; then
        DOWNLOAD_SUCCESS=1
        log "Downloaded with fetch"
    fi
fi

# Check success
if [ $DOWNLOAD_SUCCESS -eq 0 ]; then
    error "Download failed with all methods. Check network or download manually from $SCRIPT_URL"
fi

# Verify file
if [ ! -s "$TEMP_SCRIPT" ]; then
    error "Downloaded file is empty"
fi

if ! head -1 "$TEMP_SCRIPT" 2>/dev/null | grep -q '^#!/'; then
    error "Downloaded file is not a script"
fi

log "Downloaded $(wc -l < "$TEMP_SCRIPT" 2>/dev/null || echo "?") lines. Executing..."

# Execute
chmod +x "$TEMP_SCRIPT"
if [ "$OS_TYPE" = "freebsd" ]; then
    exec /bin/sh "$TEMP_SCRIPT"
else
    exec /bin/bash "$TEMP_SCRIPT"
fi