#!/bin/sh
# OpenWrt Xray Proxy Installer
# Usage: sh <(curl -fsSL https://f.n1kt.ru/xray.sh)

set -e

LOGTAG="xray-installer"
INIT_SCRIPT="/etc/init.d/xray-proxy"
REMOTE_INIT="http://f.n1kt.ru/xray-proxy"
CONFIG_SAMPLE="http://f.n1kt.ru/config.json.sample"

log() {
    echo "[INSTALL] $1"
    logger -t "$LOGTAG" "$1" 2>/dev/null || true
}

error() {
    echo "[ERROR] $1" >&2
    log "ERROR: $1"
    exit 1
}

check_openwrt() {
    if [ ! -f "/etc/openwrt_release" ] && ! grep -q "OpenWrt" /etc/*release 2>/dev/null; then
        error "This script is for OpenWrt only. Detected: $(cat /etc/*release 2>/dev/null | head -1)"
    fi
    log "✓ OpenWrt detected"
}

install_curl_if_needed() {
    if ! command -v curl >/dev/null 2>&1; then
        log "curl not found, installing via opkg..."
        opkg update >/dev/null 2>&1 || true
        opkg install curl || error "Failed to install curl"
        log "✓ curl installed"
    fi
}

check_deps() {
    local missing=""
    
    # curl уже установлен выше, проверяем остальное
    for pkg in nftables ca-bundle; do
        if ! opkg list-installed 2>/dev/null | grep -q "^$pkg "; then
            if ! command -v "${pkg%%-*}" >/dev/null 2>&1; then
                missing="$missing $pkg"
            fi
        fi
    done
    
    if [ -n "$missing" ]; then
        log "Installing missing packages:$missing"
        opkg update >/dev/null 2>&1 || true
        for pkg in $missing; do
            opkg install "$pkg" || log "⚠ Failed to install $pkg"
        done
    fi
}

download_with_curl() {
    local url="$1"
    local output="$2"
    local name="$3"
    
    log "Downloading $name..."
    
    if curl -L --limit-rate 300k -f -s -S --connect-timeout 20 --max-time 120 "$url" -o "$output.tmp" 2>/dev/null; then
        if [ -s "$output.tmp" ]; then
            mv "$output.tmp" "$output"
            chmod +x "$output"
            log "✓ $name downloaded successfully"
            return 0
        fi
    fi
    
    rm -f "$output.tmp" 2>/dev/null
    return 1
}

download_init_script() {
    log "Downloading init script..."
    
    if download_with_curl "$REMOTE_INIT" "$INIT_SCRIPT" "init script"; then
        log "✓ Init script installed: $INIT_SCRIPT"
        return 0
    fi
    
    error "Failed to download init script"
}

setup_config() {
    if [ ! -f "/root/config.json" ]; then
        log "Config not found. Downloading sample..."
        if curl -L --limit-rate 300k -f -s -S --connect-timeout 20 --max-time 60 "$CONFIG_SAMPLE" -o "/root/config.json.sample" 2>/dev/null; then
            echo "⚠ Sample config saved to /root/config.json.sample"
            echo "  Please edit it and save as /root/config.json before first start"
        else
            log "⚠ Could not download sample config, create /root/config.json manually"
        fi
    else
        log "✓ Config found: /root/config.json"
    fi
}

enable_service() {
    log "Enabling service..."
    /etc/init.d/xray-proxy enable || error "Failed to enable service"
    log "✓ Service enabled"
}

finalize() {
    sync
    echo ""
    echo "========================================"
    echo " Installation complete!"
    echo "========================================"
    echo ""
    echo "Next steps:"
    echo "  1. Edit /root/config.json with your Xray settings"
    echo "  2. Start the service: /etc/init.d/xray-proxy start"
    echo "  3. Check logs: logread | grep xray-proxy"
    echo ""
    echo "⚠ IMPORTANT: If binaries are in /tmp, they will be cleared on reboot!"
    echo "  The init script will re-download them automatically on next boot."
    echo "  Ensure your config.json is in persistent storage (/root/)"
    echo ""
    echo " Reboot recommended: 'reboot'"
    echo ""
}

main() {
    echo "OpenWrt Xray Proxy Installer (curl edition)"
    echo ""
    
    check_openwrt
    install_curl_if_needed
    check_deps
    download_init_script
    setup_config
    enable_service
    finalize
}

main "$@"
