#!/usr/bin/env bash
# ScanGuard — one-line installer.
#
#   sudo bash <(curl -Ls https://1344.pl/downloads/scanguard/get.sh)         interactive: asks for the bot token and your Telegram ID
#   BOT_TOKEN=123:abc ADMIN_IDS=111 sudo -E bash get.sh --yes                no questions
#   SCANGUARD_BUNDLE=./scanguard-1.0.0-all.tar.gz sudo bash get.sh           install from a local file or URL
#
# It downloads the release bundle, checks its SHA-256, unpacks it to a temporary directory and runs install.sh.
set -Eeuo pipefail

RELEASE_BASE=${SCANGUARD_RELEASE_BASE:-https://1344.pl/downloads/scanguard}
[[ $EUID -eq 0 ]] || { echo "Run as root: sudo bash get.sh" >&2; exit 1; }
command -v curl >/dev/null || {
  if command -v apt-get >/dev/null; then apt-get update -qq && apt-get install -y -qq curl ca-certificates >/dev/null
  elif command -v dnf >/dev/null; then dnf install -y -q curl ca-certificates >/dev/null
  elif command -v yum >/dev/null; then yum install -y -q curl ca-certificates >/dev/null
  else echo "curl is required" >&2; exit 1; fi
}

TMP=$(mktemp -d /tmp/scanguard-get.XXXXXX); trap 'rm -rf "$TMP"' EXIT
SRC=${SCANGUARD_BUNDLE:-}
if [[ -z $SRC ]]; then
  NAME=$(curl -fsSL "$RELEASE_BASE/latest.txt" | tr -d '\r\n ') || { echo "Could not read $RELEASE_BASE/latest.txt" >&2; exit 1; }
  [[ $NAME =~ ^scanguard-[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 [[ ${SCANGUARD_SKIP_SHA:-} == 1 ]]; then echo "Warning: checksum check skipped" >&2
  else echo "No .sha256 file next to the bundle; refusing to install unverified code (SCANGUARD_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 && -d $DIR/scanguard ]] || { echo "The bundle is incomplete (install.sh or scanguard/ missing)." >&2; exit 1; }
cd "$DIR"
rc=0; bash install.sh "$@" || rc=$?
exit $rc
