#!/bin/sh
# ── OpenWrt Gateway Online Installer ─────────────────────────────
# One-liner usage (run on the OpenWrt router):
#
#   wget -qO- http://124.70.180.22:8080/openwrt-gateway/install-openwrt-gateway.sh | sh
#
# This script auto-detects the router's CPU architecture, downloads
# the correct package, extracts it, and runs the full installer.
# ─────────────────────────────────────────────────────────────────

set -e

BASE_URL="http://124.70.180.22:8080/openwrt-gateway"
WORK_DIR="/tmp/openwrt-gateway-installer"

RED='\033[0;31m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
NC='\033[0m'

info()  { printf "${CYAN}[INFO]${NC}  %s\n" "$1"; }
fail()  { printf "${RED}[FAIL]${NC}  %s\n" "$1"; exit 1; }

# ── Detect architecture ─────────────────────────────────────────
MACHINE=$(uname -m)
case "$MACHINE" in
    aarch64)   ARCH="arm64"  ;;
    mipsel|mips) ARCH="mipsle" ;;
    x86_64)    ARCH="amd64"  ;;
    *)         fail "Unsupported architecture: $MACHINE" ;;
esac
info "Detected architecture: $MACHINE -> $ARCH"

# ── Fetch latest version ────────────────────────────────────────
info "Fetching latest version info..."
VERSION=$(wget -qO- "${BASE_URL}/latest.txt" 2>/dev/null || echo "")
if [ -z "$VERSION" ]; then
    fail "Could not fetch version from ${BASE_URL}/latest.txt"
fi
VERSION=$(echo "$VERSION" | tr -d '[:space:]')
info "Latest version: $VERSION"

# ── Download package ────────────────────────────────────────────
PACKAGE_NAME="openwrt-gateway-${VERSION}-${ARCH}"
ARCHIVE="${PACKAGE_NAME}.tar.gz"
DOWNLOAD_URL="${BASE_URL}/${ARCHIVE}"

info "Downloading $ARCHIVE ..."
rm -rf "$WORK_DIR"
mkdir -p "$WORK_DIR"
cd "$WORK_DIR"

wget -q "$DOWNLOAD_URL" -O "$ARCHIVE" || fail "Download failed: $DOWNLOAD_URL"
info "Download complete ($(wc -c < "$ARCHIVE" | tr -d ' ') bytes)"

# ── Extract and install ─────────────────────────────────────────
info "Extracting..."
tar xzf "$ARCHIVE"
cd "$PACKAGE_NAME"

info "Running installer..."
sh ./install.sh

# ── Cleanup ──────────────────────────────────────────────────────
info "Cleaning up temporary files..."
rm -rf "$WORK_DIR"

printf "${GREEN}[DONE]${NC}  Online installation complete.\n"
