#!/usr/bin/env bash
# 1344 Network Panel — one-line installer (3x-ui style).
#
#   bash <(curl -Ls https://YOUR-HOST/get.sh)                 quick install: random secret path and port, admin login printed at the end
#   bash <(curl -Ls https://YOUR-HOST/get.sh) --interactive   ask every question instead
#   PANEL_BUNDLE=./1344-panel-0.5.0-amd64.tar.gz bash get.sh  install from a local file or URL (no download host needed)
#
# It downloads the release bundle, checks its SHA-256, unpacks it to a temporary directory and runs install.sh.
# Publish the bundles built by tools/make-bundle.sh (the .tar.gz, its .sha256 and latest.txt) at RELEASE_BASE.
set -Eeuo pipefail

RELEASE_BASE=${PANEL_RELEASE_BASE:-https://1344.pl/downloads/network-panel}   # e.g. https://github.com/<owner>/<repo>/releases/latest/download  — set when the release is published
[[ $EUID -eq 0 ]] || { echo "Run as root: sudo bash get.sh" >&2; exit 1; }
command -v curl >/dev/null || { apt-get update -qq && apt-get install -y -qq curl ca-certificates >/dev/null; }

case "$(uname -m)" in x86_64|amd64) ARCH=amd64;; aarch64|arm64) ARCH=arm64;; *) echo "Unsupported CPU architecture $(uname -m)" >&2; exit 1;; esac

MODE=--quick; ARGS=()
for a in "$@"; do case "$a" in --interactive) MODE=;; *) ARGS+=("$a");; esac; done

TMP=$(mktemp -d /tmp/1344-get.XXXXXX); trap 'rm -rf "$TMP"' EXIT
SRC=${PANEL_BUNDLE:-}
if [[ -z $SRC ]]; then
  [[ -n $RELEASE_BASE ]] || { echo "No download address is set. Use PANEL_BUNDLE=<file or URL> or PANEL_RELEASE_BASE=<url>." >&2; exit 1; }
  NAME=$(curl -fsSL "$RELEASE_BASE/latest.txt" | tr -d '\r\n ' ) || { echo "Could not read $RELEASE_BASE/latest.txt" >&2; exit 1; }
  NAME=${NAME//-amd64.tar.gz/-$ARCH.tar.gz}; NAME=${NAME//-arm64.tar.gz/-$ARCH.tar.gz}
  [[ $NAME =~ ^1344-panel-[A-Za-z0-9._-]+\.tar\.gz$ ]] || { echo "Unexpected bundle name in latest.txt" >&2; exit 1; }
  SRC=$RELEASE_BASE/$NAME
fi

echo "Fetching $SRC"
if [[ -f $SRC ]]; then cp "$SRC" "$TMP/bundle.tar.gz"; else curl -fL --retry 3 -o "$TMP/bundle.tar.gz" "$SRC"; fi

if [[ ! -f $SRC || -f $SRC.sha256 ]]; then
  if [[ -f $SRC ]]; then want=$(cut -d' ' -f1 "$SRC.sha256")
  else want=$(curl -fsSL "$SRC.sha256" 2>/dev/null | cut -d' ' -f1 || true); fi
  if [[ -n ${want:-} ]]; then
    got=$(sha256sum "$TMP/bundle.tar.gz" | cut -d' ' -f1)
    [[ $got == "$want" ]] || { echo "SHA-256 mismatch: the download is damaged or was tampered with." >&2; exit 1; }
    echo "SHA-256 verified"
  elif [[ ${PANEL_SKIP_SHA:-} == 1 ]]; then echo "Warning: checksum check skipped" >&2
  else echo "No .sha256 file next to the bundle; refusing to install unverified code (PANEL_SKIP_SHA=1 overrides)." >&2; exit 1; fi
fi

tar -xzf "$TMP/bundle.tar.gz" -C "$TMP"
DIR=$(find "$TMP" -maxdepth 2 -name install.sh -printf '%h\n' | head -1)
[[ -n $DIR && -x $DIR/bin/panel ]] || { echo "The bundle is incomplete (install.sh or bin/panel missing)." >&2; exit 1; }
cd "$DIR"
rc=0; bash install.sh $MODE "${ARGS[@]}" || rc=$?
exit $rc
