#!/usr/bin/env bash
set -euo pipefail
VERSION="1.3.8"
MIRROR="${SCPANEL_MIRROR:-https://mirror.sikon.com.bd/scpanel}"
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
ARCHIVE="$TMP/scpanel-v${VERSION}.tar.gz"
echo "Sikon SC Panel v${VERSION}"
curl -fL --retry 3 --connect-timeout 15 --max-time 120 "${MIRROR}/scpanel-v${VERSION}.tar.gz" -o "$ARCHIVE"
tar -xzf "$ARCHIVE" -C "$TMP"
SRC="$TMP/scpanel-v${VERSION}"
# Accept the canonical archive root plus legacy case variants from older mirror builds.
if [[ ! -f "$SRC/requirements.txt" || ! -f "$SRC/app/app.py" || ! -f "$SRC/scripts/install-local.sh" ]]; then
  SRC=""
  while IFS= read -r -d '' candidate; do
    if [[ -f "$candidate/requirements.txt" && -f "$candidate/app/app.py" && -f "$candidate/scripts/install-local.sh" ]]; then
      SRC="$candidate"
      break
    fi
  done < <(find "$TMP" -mindepth 1 -maxdepth 2 -type d -print0)
fi
[[ -n "$SRC" ]] || { echo "Package integrity check failed: required SCpanel files are missing from the archive"; exit 1; }
systemctl stop scpanel-admin scpanel-user scpanel-admin-http 2>/dev/null || true
rm -rf /opt/scpanel
install -d /opt/scpanel
cp -a "$SRC/." /opt/scpanel/
SCPANEL_VERSION="$VERSION" bash /opt/scpanel/scripts/install-local.sh
