#!/usr/bin/env bash
set -euo pipefail

SCRIPT_PATH="$(readlink -f "${BASH_SOURCE[0]}")"
SCRIPT_DIR="$(cd "$(dirname "$SCRIPT_PATH")" && pwd)"
ROOT_DIR="$SCRIPT_DIR"

RELEASE_VERSION="${1:-}"
OUTPUT_DIR_INPUT="${2:-}"
SOURCE_ROOT_DIR="${SOURCE_ROOT_DIR:-}"
WINDOWS_ARTIFACTS_DIR="${WINDOWS_ARTIFACTS_DIR:-}"
DEFAULT_BUILD_HOME="${HOME}"

if [[ "$DEFAULT_BUILD_HOME" == "/root" ]]; then
  DEFAULT_BUILD_HOME="$(getent passwd 1000 | cut -d: -f6 || true)"
  DEFAULT_BUILD_HOME="${DEFAULT_BUILD_HOME:-/root}"
fi

if [ "${BASH_SOURCE[0]}" = "$0" ] && [[ ! "$RELEASE_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  echo "Expected release version in the form x.y.z" >&2
  exit 1
fi
APK_INTERNAL_VERSION="$RELEASE_VERSION"

GIT_COMMIT_SHA="$(git -C "$ROOT_DIR" rev-parse --short HEAD 2>/dev/null || echo "unknown")"

WSL_NATIVE_ROOT="${WSL_NATIVE_ROOT:-$DEFAULT_BUILD_HOME/build/tachyon}"
WORK_DIR="${WORK_DIR:-$ROOT_DIR/.wsl-build}"
SDK_WORK_DIR="${SDK_WORK_DIR:-$WORK_DIR/sdk}"
SDK_CACHE_DIR="${SDK_CACHE_DIR:-$DEFAULT_BUILD_HOME/.cache/tachyon/openwrt-sdk}"
IPK_SDK_URL="${IPK_SDK_URL:-https://downloads.openwrt.org/releases/24.10.6/targets/x86/64/openwrt-sdk-24.10.6-x86-64_gcc-13.3.0_musl.Linux-x86_64.tar.zst}"
APK_SDK_URL="${APK_SDK_URL:-https://downloads.openwrt.org/releases/25.12.3/targets/x86/64/openwrt-sdk-25.12.3-x86-64_gcc-14.3.0_musl.Linux-x86_64.tar.zst}"

BACKEND_DESCRIPTION="Rule-based Tachyon backend with tachyon-core orchestration"
APP_DESCRIPTION="Rule-based Tachyon LuCI app with tachyon-core orchestration"
I18N_DESCRIPTION="Translation for luci-app-tachyon - Русский (Russian)"
MAINTAINER="Dushnilin <dushnilin@gmail.com>"
PROJECT_URL="https://github.com/Dushnilin/tachyon"
BACKEND_CONFLICTS_IPK="https-dns-proxy, nextdns, luci-app-passwall, luci-app-passwall2"
BACKEND_DEPENDS_IPK="libc, ca-bundle, curl, openssl-util, ucode, ucode-mod-fs, ucode-mod-uci, coreutils-base64, coreutils-timeout, bind-dig, nftables, ip-full, kmod-nft-tproxy, kmod-tun, kmod-inet-diag"
BACKEND_DEPENDS_APK="bind-dig ca-bundle coreutils-base64 coreutils-timeout curl ip-full kmod-inet-diag kmod-nft-tproxy kmod-tun libc nftables openssl-util ucode ucode-mod-fs ucode-mod-uci !https-dns-proxy !nextdns !luci-app-passwall !luci-app-passwall2"
APP_DEPENDS_IPK="libc, luci-base, tachyon"
APP_DEPENDS_APK="libc luci-base tachyon"

APT_PACKAGES=(
  build-essential
  curl
  fakeroot
  file
  gawk
  git
  patch
  python3
  rsync
  tar
  unzip
  util-linux
  wget
  xz-utils
  zstd
)

copy_to_native_root() {
  local target_root="${WSL_NATIVE_ROOT%/}"
  local target_output
  local source_root="${SOURCE_ROOT_DIR:-$ROOT_DIR}"
  local windows_output="${WINDOWS_ARTIFACTS_DIR:-$source_root/dist/release-final}"

  mkdir -p "$target_root"
  rsync -a --delete \
    --exclude ".git" \
    --exclude ".wsl-build" \
    --exclude "dist" \
    --exclude ".idea" \
    --exclude "sandbox" \
    --exclude "fe-app-tachyon/node_modules" \
    --exclude "fe-app-tachyon/tests" \
    "$ROOT_DIR/" "$target_root/"
  rm -rf \
    "$target_root/.idea" \
    "$target_root/sandbox" \
    "$target_root/fe-app-tachyon/node_modules" \
    "$target_root/fe-app-tachyon/tests"

  if [[ -n "$OUTPUT_DIR_INPUT" ]]; then
    target_output="$OUTPUT_DIR_INPUT"
  else
    target_output="$target_root/dist/release-final"
  fi

  echo "Synced repository to native WSL path: $target_root" >&2
  export SOURCE_ROOT_DIR="$source_root"
  export WINDOWS_ARTIFACTS_DIR="$windows_output"
  exec bash "$target_root/build.sh" "$RELEASE_VERSION" "$target_output"
}

ensure_native_root() {
  case "$ROOT_DIR" in
    /mnt/*)
      copy_to_native_root
      ;;
  esac
}

ensure_host_deps() {
  local missing=()
  local commands=(
    ar
    curl
    fakeroot
    file
    gcc
    git
    make
    python3
    rsync
    sha256sum
    tar
    unshare
    wget
    zstd
  )

  for cmd in "${commands[@]}"; do
    if ! command -v "$cmd" >/dev/null 2>&1; then
      missing+=("$cmd")
    fi
  done

  if (( ${#missing[@]} == 0 )); then
    return 0
  fi

  echo "Installing missing host dependencies: ${APT_PACKAGES[*]}" >&2
  if [[ "$(id -u)" -eq 0 ]]; then
    rm -f /etc/apt/sources.list.d/google-chrome.list 2>/dev/null || true
    apt-get update
    DEBIAN_FRONTEND=noninteractive apt-get install -y "${APT_PACKAGES[@]}"
    return 0
  fi

  if command -v sudo >/dev/null 2>&1 && sudo -n true >/dev/null 2>&1; then
    sudo rm -f /etc/apt/sources.list.d/google-chrome.list 2>/dev/null || true
    sudo apt-get update
    sudo DEBIAN_FRONTEND=noninteractive apt-get install -y "${APT_PACKAGES[@]}"
    return 0
  fi

  echo "Missing build dependencies and no passwordless sudo/root available: ${missing[*]}" >&2
  exit 1
}

have_passwordless_sudo() {
  command -v sudo >/dev/null 2>&1 && sudo -n true >/dev/null 2>&1
}

have_unshare_root() {
  command -v unshare >/dev/null 2>&1 && unshare -r true >/dev/null 2>&1
}

download_sdk_archive() {
  local url="$1"
  local archive_path="$SDK_CACHE_DIR/$(basename "$url")"
  local rel_path="${url#https://downloads.openwrt.org/}"
  local candidate_urls=(
    "$url"
    "https://mirror-03.infra.openwrt.org/${rel_path}"
    "https://ftp.fau.de/openwrt/${rel_path}"
  )
  local candidate

  mkdir -p "$SDK_CACHE_DIR"
  if [[ ! -f "$archive_path" ]]; then
    for candidate in "${candidate_urls[@]}"; do
      echo "Downloading SDK: $candidate" >&2
      rm -f "$archive_path.part"
      if curl -4 -fL --retry 2 --connect-timeout 10 --speed-time 20 --speed-limit 102400 -o "$archive_path.part" "$candidate"; then
        mv "$archive_path.part" "$archive_path"
        break
      fi
    done
    if [[ ! -f "$archive_path" ]]; then
      echo "Failed to download SDK from all mirrors: $url" >&2
      exit 1
    fi
  fi

  printf '%s\n' "$archive_path"
}

extract_sdk() {
  local kind="$1"
  local archive_path="$2"
  local sdk_url="$3"
  local destination="$SDK_WORK_DIR/$kind"
  local marker_file="$destination/.tachyon-sdk-url"
  local temp_dir
  local extracted_root

  mkdir -p "$SDK_WORK_DIR"
  if [[ -d "$destination" && -f "$marker_file" ]] && [[ "$(cat "$marker_file")" == "$sdk_url" ]]; then
    printf '%s\n' "$destination"
    return 0
  fi

  rm -rf "$destination"
  temp_dir="$(mktemp -d "$SDK_WORK_DIR/.${kind}.XXXXXX")"
  tar --zstd -xf "$archive_path" -C "$temp_dir"
  extracted_root="$(find "$temp_dir" -mindepth 1 -maxdepth 1 -type d | head -n 1)"
  mv "$extracted_root" "$destination"
  printf '%s\n' "$sdk_url" > "$marker_file"
  rmdir "$temp_dir" 2>/dev/null || true

  printf '%s\n' "$destination"
}

ensure_po2lmo() {
  local ipk_sdk_dir="$1"
  local po2lmo_bin="$ipk_sdk_dir/staging_dir/hostpkg/bin/po2lmo"
  local luci_src_dir="$ipk_sdk_dir/feeds/luci/modules/luci-base/src"

  if [[ -x "$po2lmo_bin" ]]; then
    printf '%s\n' "$po2lmo_bin"
    return 0
  fi

  mkdir -p "$ipk_sdk_dir"
  (
    cd "$ipk_sdk_dir"
    if [[ ! -d feeds/luci/modules/luci-base/src ]]; then
      # A previous interrupted update can leave a partial feeds/luci behind;
      # re-clone from scratch rather than compiling against missing sources.
      rm -rf feeds/luci
      mkdir -p feeds
      if ! (
        git clone --depth 1 --filter=blob:none --sparse https://github.com/openwrt/luci.git feeds/luci >&2 &&
        git -C feeds/luci sparse-checkout set modules/luci-base/src >&2
      ); then
        rm -rf feeds/luci
        git clone --depth 1 https://github.com/openwrt/luci.git feeds/luci >&2 || true
      fi
    fi
  )

  if [[ ! -f "$luci_src_dir/po2lmo.c" ]]; then
    echo "po2lmo sources unavailable under $luci_src_dir" >&2
    return 1
  fi

  if [[ ! -x "$luci_src_dir/po2lmo" ]]; then
    # Upstream luci dropped template_lmo.c from the tree: po2lmo now links
    # against src/lib/lmo and a lemon-generated plural_formula, so only the
    # in-tree Makefile knows how to build it.
    make -C "$luci_src_dir" po2lmo >&2 || true
  fi

  if [[ -x "$luci_src_dir/po2lmo" ]]; then
    printf '%s\n' "$luci_src_dir/po2lmo"
    return 0
  fi

  # Never print a path to a binary that does not exist: the caller would die
  # later with a confusing permission/not-found error.
  echo "po2lmo compilation failed; cannot build LuCI i18n package" >&2
  return 1
}

ensure_host_tools() {
  local host_tools_dir="$SDK_CACHE_DIR/host-tools-v1"
  local marker_file="$host_tools_dir/.tachyon-sdk-url"
  local apk_archive
  local temp_dir
  local extracted_root
  local built_po2lmo

  mkdir -p "$host_tools_dir/bin" "$host_tools_dir/lib"

  if [[ ! -x "$host_tools_dir/bin/ipkg-build" || ! -x "$host_tools_dir/bin/apk" || ! -x "$host_tools_dir/bin/.apk.bin" || ! -f "$host_tools_dir/lib/ld-linux-x86-64.so.2" || ! -f "$host_tools_dir/lib/runas.so" || ! -f "$marker_file" ]] || [[ "$(cat "$marker_file")" != "$APK_SDK_URL" ]]; then
    if [[ -x "$SDK_WORK_DIR/apk/scripts/ipkg-build" && -x "$SDK_WORK_DIR/apk/staging_dir/host/bin/apk" && -x "$SDK_WORK_DIR/apk/staging_dir/host/bin/.apk.bin" ]]; then
      cp -f "$SDK_WORK_DIR/apk/scripts/ipkg-build" "$host_tools_dir/bin/ipkg-build"
      cp -f "$SDK_WORK_DIR/apk/staging_dir/host/bin/apk" "$host_tools_dir/bin/apk"
      cp -f "$SDK_WORK_DIR/apk/staging_dir/host/bin/.apk.bin" "$host_tools_dir/bin/.apk.bin"
      cp -af "$SDK_WORK_DIR/apk/staging_dir/host/lib"/ld-linux* \
        "$SDK_WORK_DIR/apk/staging_dir/host/lib"/runas.so \
        "$SDK_WORK_DIR/apk/staging_dir/host/lib"/libc.so* \
        "$SDK_WORK_DIR/apk/staging_dir/host/lib"/libpthread.so* \
        "$SDK_WORK_DIR/apk/staging_dir/host/lib"/libdl.so* \
        "$SDK_WORK_DIR/apk/staging_dir/host/lib"/librt.so* \
        "$SDK_WORK_DIR/apk/staging_dir/host/lib"/libm.so* \
        "$SDK_WORK_DIR/apk/staging_dir/host/lib"/libgcc_s.so* \
        "$host_tools_dir/lib/"
    else
      apk_archive="$(download_sdk_archive "$APK_SDK_URL")"
      mkdir -p "$SDK_WORK_DIR"
      temp_dir="$(mktemp -d "$SDK_WORK_DIR/.host-tools.XXXXXX")"
      tar --zstd -xf "$apk_archive" -C "$temp_dir" --wildcards \
        '*/scripts/ipkg-build' \
        '*/staging_dir/host/bin/apk' \
        '*/staging_dir/host/bin/.apk.bin' \
        '*/staging_dir/host/lib/ld-linux*' \
        '*/staging_dir/host/lib/runas.so' \
        '*/staging_dir/host/lib/libc.so*' \
        '*/staging_dir/host/lib/libpthread.so*' \
        '*/staging_dir/host/lib/libdl.so*' \
        '*/staging_dir/host/lib/librt.so*' \
        '*/staging_dir/host/lib/libm.so*' \
        '*/staging_dir/host/lib/libgcc_s.so*'
      extracted_root="$(find "$temp_dir" -mindepth 1 -maxdepth 1 -type d | head -n 1)"
      cp -f "$extracted_root/scripts/ipkg-build" "$host_tools_dir/bin/ipkg-build"
      cp -f "$extracted_root/staging_dir/host/bin/apk" "$host_tools_dir/bin/apk"
      cp -f "$extracted_root/staging_dir/host/bin/.apk.bin" "$host_tools_dir/bin/.apk.bin"
      cp -af "$extracted_root/staging_dir/host/lib/"* "$host_tools_dir/lib/"
      rm -rf "$temp_dir"
      if [[ "${CI:-}" == "true" && "${KEEP_SDK_ARCHIVES:-0}" != "1" ]]; then
        rm -f "$apk_archive"
      fi
    fi
    chmod 0755 "$host_tools_dir/bin/ipkg-build" "$host_tools_dir/bin/apk" "$host_tools_dir/bin/.apk.bin"
    printf '%s\n' "$APK_SDK_URL" > "$marker_file"
  fi

  if [[ ! -x "$host_tools_dir/bin/po2lmo" ]]; then
    if [[ -x "$SDK_WORK_DIR/ipk/feeds/luci/modules/luci-base/src/po2lmo" ]]; then
      cp -f "$SDK_WORK_DIR/ipk/feeds/luci/modules/luci-base/src/po2lmo" "$host_tools_dir/bin/po2lmo"
    else
      built_po2lmo="$(ensure_po2lmo "$SDK_WORK_DIR/po2lmo-build")"
      cp -f "$built_po2lmo" "$host_tools_dir/bin/po2lmo"
    fi
    chmod 0755 "$host_tools_dir/bin/po2lmo"
  fi

  printf '%s\n' "$host_tools_dir"
}

make_dir() {
  mkdir -p "$1"
}

normalize_package_root_modes() {
  local package_root="$1"

  find "$package_root" -type d -exec chmod 0755 {} +
  find "$package_root" -type f -exec chmod 0644 {} +
}

build_backend_root() {
  local output_root="$1"

  if command -v node >/dev/null 2>&1 && [[ -f "$ROOT_DIR/tests/lib/ucode_forward_refs.js" ]]; then
    node "$ROOT_DIR/tests/lib/ucode_forward_refs.js" "$ROOT_DIR/tachyon/files/usr/lib"
  fi

  rm -rf "$output_root"
  make_dir "$output_root/etc/init.d"
  make_dir "$output_root/etc/config"
  make_dir "$output_root/etc/hotplug.d/iface"
  make_dir "$output_root/lib/upgrade/keep.d"
  make_dir "$output_root/usr/bin"
  make_dir "$output_root/usr/sbin"
  make_dir "$output_root/usr/lib/tachyon"
  make_dir "$output_root/usr/lib/tachyon/defaults"
  make_dir "$output_root/usr/lib/cgi-bin"
  make_dir "$output_root/usr/share/tachyon"
  make_dir "$output_root/usr/share/rpcd/acl.d"

  install -m 0755 "$ROOT_DIR/tachyon/files/etc/init.d/tachyon" "$output_root/etc/init.d/tachyon"
  install -m 0755 "$ROOT_DIR/tachyon/files/etc/init.d/tachyon-torrserver-direct" \
    "$output_root/etc/init.d/tachyon-torrserver-direct"
  install -m 0644 "$ROOT_DIR/tachyon/files/etc/config/tachyon" "$output_root/etc/config/tachyon"
  install -m 0644 "$ROOT_DIR/tachyon/files/lib/upgrade/keep.d/tachyon" "$output_root/lib/upgrade/keep.d/tachyon"
  install -m 0755 "$ROOT_DIR/tachyon/files/usr/bin/tachyon" "$output_root/usr/bin/tachyon"
  install -m 0755 "$ROOT_DIR/tachyon/files/usr/bin/tachyon-read" "$output_root/usr/bin/tachyon-read"
  # The rpcd ACL for /usr/bin/tachyon and /usr/bin/tachyon-read ships here rather
  # than in luci-app-tachyon, so the backend and its policy update apart. That is
  # the point of splitting the read role off the main binary; shipping the ACL
  # from the LuCI package left a stricter read role inert whenever only one of
  # the two packages was upgraded.
  install -m 0644 "$ROOT_DIR/tachyon/files/usr/share/rpcd/acl.d/luci-app-tachyon.json" \
    "$output_root/usr/share/rpcd/acl.d/luci-app-tachyon.json"
  cp -a "$ROOT_DIR/tachyon/files/usr/lib/." "$output_root/usr/lib/tachyon/"

  # Mirror Package/tachyon/install from tachyon/Makefile exactly: the release
  # artifacts are built here, so any file the Makefile ships must ship here too.
  install -m 0600 "$ROOT_DIR/tachyon/files/etc/config/tachyon" "$output_root/usr/lib/tachyon/defaults/config"
  install -m 0755 "$ROOT_DIR/tachyon/files/etc/hotplug.d/iface/99-tachyon-wan-monitor" \
    "$output_root/etc/hotplug.d/iface/99-tachyon-wan-monitor"
  install -m 0755 "$ROOT_DIR/tachyon/files/usr/lib/cgi-bin/tachyon-agent" \
    "$output_root/usr/lib/cgi-bin/tachyon-agent"
  install -d -m 0755 "$output_root/www/cgi-bin"
  install -m 0755 "$ROOT_DIR/tachyon/files/www/cgi-bin/tachyon-sub" \
    "$output_root/www/cgi-bin/tachyon-sub"
  # No symlink in $output_root/www/cgi-bin: the AI agent gateway is published
  # at service start only when agent_api_token is set (issue #76).
  install -m 0644 "$ROOT_DIR/tachyon/files/usr/share/tachyon/servicecheck_profiles.json" \
    "$output_root/usr/share/tachyon/servicecheck_profiles.json"
  # Registrable-domain boundaries for Smart Detect Plus (ICANN + PRIVATE, MPL-2.0).
  install -m 0644 "$ROOT_DIR/tachyon/files/usr/share/tachyon/public-suffix-list.dat" \
    "$output_root/usr/share/tachyon/public-suffix-list.dat"
  # Curated strategy presets. Without it the fuzzer falls back to
  # downloading the file from a mirror on first use.
  install -m 0644 "$ROOT_DIR/tachyon/files/usr/share/tachyon/dpi-presets.json" \
    "$output_root/usr/share/tachyon/dpi-presets.json"

  local commit_sha="${GIT_COMMIT_SHA:-}"
  if [[ -z "$commit_sha" || "$commit_sha" == "unknown" ]]; then
    commit_sha="$(git -C "$ROOT_DIR" rev-parse --short HEAD 2>/dev/null || echo "unknown")"
  fi

  sed -i -e "s/__COMPILED_VERSION_VARIABLE__/${RELEASE_VERSION}/g" \
    -e "s/__COMPILED_COMMIT_SHA__/${commit_sha}/g" \
    "$output_root/usr/lib/tachyon/core/constants.uc"

  normalize_package_root_modes "$output_root"
  chmod 0755 "$output_root/etc/init.d/tachyon" "$output_root/usr/bin/tachyon" \
    "$output_root/usr/bin/tachyon-read" \
    "$output_root/etc/init.d/tachyon-torrserver-direct" \
    "$output_root/etc/hotplug.d/iface/99-tachyon-wan-monitor" \
    "$output_root/usr/lib/tachyon/bin/wget" \
    "$output_root/usr/lib/cgi-bin/tachyon-agent" \
    "$output_root/www/cgi-bin/tachyon-sub"
  # Contains the Telegram bot token placeholder and receives user secrets.
  chmod 0600 "$output_root/etc/config/tachyon" "$output_root/usr/lib/tachyon/defaults/config"
}

build_app_root() {
  local output_root="$1"

  rm -rf "$output_root"
  make_dir "$output_root/www"

  if [[ -d "$ROOT_DIR/luci-app-tachyon/htdocs" ]]; then
    cp -a "$ROOT_DIR/luci-app-tachyon/htdocs/." "$output_root/www/"
  fi

  if [[ -d "$ROOT_DIR/luci-app-tachyon/root" ]]; then
    cp -a "$ROOT_DIR/luci-app-tachyon/root/." "$output_root/"
  fi

  if [[ -f "$output_root/www/luci-static/resources/view/tachyon/main.js" ]]; then
    sed -i -e "s/__COMPILED_VERSION_VARIABLE__/${RELEASE_VERSION}/g" \
      "$output_root/www/luci-static/resources/view/tachyon/main.js"
  fi

  normalize_package_root_modes "$output_root"
  find "$output_root/etc/uci-defaults" -type f -exec chmod 0755 {} + 2>/dev/null || true
}

build_i18n_root() {
  local output_root="$1"
  local po2lmo_bin="$2"
  local lmo_path="$output_root/usr/lib/lua/luci/i18n/tachyon.ru.lmo"

  rm -rf "$output_root"
  make_dir "$output_root/etc/uci-defaults"
  make_dir "$(dirname "$lmo_path")"

  cat > "$output_root/etc/uci-defaults/luci-i18n-tachyon-ru" <<'EOF'
uci set luci.languages.ru='Русский (Russian)'; uci commit luci
EOF

  "$po2lmo_bin" "$ROOT_DIR/luci-app-tachyon/po/ru/tachyon.po" "$lmo_path"

  normalize_package_root_modes "$output_root"
  find "$output_root/etc/uci-defaults" -type f -exec chmod 0755 {} + 2>/dev/null || true
}

generate_apk_metadata_files() {
  local package_name="$1"
  local package_root="$2"
  local conffile_path="${3:-}"
  local list_file="$package_root/lib/apk/packages/${package_name}.list"

  make_dir "$(dirname "$list_file")"
  (
    cd "$package_root"
    find . -type f ! -path './lib/apk/packages/*' | LC_ALL=C sort | sed 's#^\./#/#'
  ) > "$list_file"

  if [[ -n "$conffile_path" ]]; then
    local conffiles_file="$package_root/lib/apk/packages/${package_name}.conffiles"
    local conffiles_static_file="$package_root/lib/apk/packages/${package_name}.conffiles_static"
    local hash_value

    hash_value="$(sha256sum "$package_root$conffile_path" | awk '{print $1}')"
    printf '%s\n' "$conffile_path" > "$conffiles_file"
    printf '%s %s\n' "$conffile_path" "$hash_value" > "$conffiles_static_file"
  fi
}

installed_size_bytes() {
  du -sk "$1" | awk '{print $1 * 1024}'
}

write_backend_ipk_control() {
  local control_dir="$1"
  local installed_size="$2"

  rm -rf "$control_dir"
  make_dir "$control_dir"

  cat > "$control_dir/control" <<EOF
Package: tachyon
Version: ${RELEASE_VERSION}
Depends: ${BACKEND_DEPENDS_IPK}
Conflicts: ${BACKEND_CONFLICTS_IPK}
License: GPL-2.0-or-later
Section: net
URL: ${PROJECT_URL}
Maintainer: ${MAINTAINER}
Architecture: all
Installed-Size: ${installed_size}
Description: ${BACKEND_DESCRIPTION}
EOF

  cat > "$control_dir/conffiles" <<'EOF'
/etc/config/tachyon
EOF

  cat > "$control_dir/postinst" <<'EOF'
#!/bin/sh
[ -n "${IPKG_INSTROOT}" ] && exit 0

_backup_external_configs() {
	_bdir="/etc/tachyon/external-configs-backup"
	for _comp in zapret zapret2 byedpi wdtt qwdtt olcrtc sing-box; do
		_cdir="$_bdir/$_comp"
		case "$_comp" in
			zapret) _srcs="/etc/config/zapret /opt/zapret/config /opt/zapret/ipset" ;;
			zapret2) _srcs="/etc/config/zapret2 /opt/zapret2/config /opt/zapret2/ipset" ;;
			byedpi) _srcs="/etc/config/byedpi /etc/byedpi" ;;
			wdtt|qwdtt) _srcs="/etc/config/wdtt /etc/wdtt /etc/qwdtt" ;;
			olcrtc) _srcs="/etc/config/olcrtc /etc/olcrtc" ;;
			sing-box) _srcs="/etc/sing-box/config.json /etc/config/sing-box" ;;
		esac
		_has_src=0
		for _s in $_srcs; do [ -e "$_s" ] && _has_src=1 && break; done
		[ "$_has_src" -eq 0 ] && continue
		mkdir -p "$_cdir" 2>/dev/null || continue
		for _s in $_srcs; do
			[ -e "$_s" ] || continue
			_dst="$_cdir/$(basename "$_s")"
			if [ -d "$_s" ]; then
				cp -a -n "$_s" "$_dst" 2>/dev/null || cp -a "$_s" "${_dst}.new" 2>/dev/null || true
			else
				[ -f "$_dst" ] && cmp -s "$_s" "$_dst" 2>/dev/null && continue
				cp -a "$_s" "$_dst" 2>/dev/null || true
			fi
		done
	done
}
_is_tachyon_managed() {
	_comp="$1"
	[ -f "/etc/init.d/$_comp" ] && grep -q "Tachyon managed" "/etc/init.d/$_comp" 2>/dev/null && return 0
	[ -d "/etc/tachyon/component-backups/$_comp" ] && return 0
	[ -d "/var/run/tachyon/$_comp" ] && return 0
	return 1
}

_backup_external_configs

# Stop and clean Tachyon internal steer subsystem
for _steer_svc in tachyon-steer-zapret steer; do
	if [ -f "/etc/init.d/${_steer_svc}" ]; then
		"/etc/init.d/${_steer_svc}" stop >/dev/null 2>&1 || true
		"/etc/init.d/${_steer_svc}" disable >/dev/null 2>&1 || true
		rm -f "/etc/init.d/${_steer_svc}" 2>/dev/null || true
	fi
done
rm -rf /etc/rc.d/*steer* /etc/steer /usr/lib/tachyon/steer /usr/sbin/steer /usr/bin/steer /var/run/tachyon/*steer* /tmp/*steer* 2>/dev/null || true
killall -9 steer >/dev/null 2>&1 || true
nft delete table inet steer >/dev/null 2>&1 || true

# Selective cleanup of external components only if Tachyon-managed
if [ -f /etc/init.d/tailscale ] && grep -q "Tachyon managed" /etc/init.d/tailscale 2>/dev/null; then
	/etc/init.d/tailscale stop >/dev/null 2>&1 || true
	/etc/init.d/tailscale disable >/dev/null 2>&1 || true
	rm -f /etc/init.d/tailscale /etc/rc.d/*tailscale* 2>/dev/null || true
	rm -rf /var/run/tachyon/tailscale /etc/tachyon/tailscale/*/native /etc/tachyon/component-backups/tailscale 2>/dev/null || true
	nft delete table inet tachyon_tailscale >/dev/null 2>&1 || true
fi
for _comp in zapret zapret2 byedpi wdtt-client qwdtt olcrtc; do
	_comp_marker="$_comp"
	case "$_comp" in wdtt-client) _comp_marker="wdtt" ;; esac
	if _is_tachyon_managed "$_comp_marker"; then
		if [ -f "/etc/init.d/${_comp}" ]; then
			"/etc/init.d/${_comp}" stop >/dev/null 2>&1 || true
			"/etc/init.d/${_comp}" disable >/dev/null 2>&1 || true
			rm -f "/etc/init.d/${_comp}" "/etc/rc.d/*${_comp}*" 2>/dev/null || true
		fi
		case "$_comp_marker" in
			zapret)
				killall -9 nfqws >/dev/null 2>&1 || true
				rm -f /usr/bin/nfqws 2>/dev/null || true
				rm -rf /opt/zapret /etc/config/zapret /var/run/tachyon/zapret* /etc/tachyon/component-backups/zapret /var/run/tachyon/component-update-checks/zapret.json 2>/dev/null || true
				for _tbl in zapret; do nft delete table inet "$_tbl" >/dev/null 2>&1 || true; nft delete table ip "$_tbl" >/dev/null 2>&1 || true; nft delete table ip6 "$_tbl" >/dev/null 2>&1 || true; done
				;;
			zapret2)
				killall -9 nfqws2 >/dev/null 2>&1 || true
				rm -f /usr/bin/nfqws2 2>/dev/null || true
				rm -rf /opt/zapret2 /etc/config/zapret2 /etc/tachyon/component-backups/zapret2 /var/run/tachyon/component-update-checks/zapret2.json 2>/dev/null || true
				for _tbl in zapret2; do nft delete table inet "$_tbl" >/dev/null 2>&1 || true; nft delete table ip "$_tbl" >/dev/null 2>&1 || true; nft delete table ip6 "$_tbl" >/dev/null 2>&1 || true; done
				;;
			byedpi)
				killall -9 ciadpi >/dev/null 2>&1 || true
				rm -f /usr/bin/ciadpi 2>/dev/null || true
				rm -rf /etc/config/byedpi /var/run/tachyon/byedpi /etc/tachyon/component-backups/byedpi /var/run/tachyon/component-update-checks/byedpi.json 2>/dev/null || true
				;;
			wdtt)
				killall -9 wdtt qwdtt-client >/dev/null 2>&1 || true
				rm -f /usr/bin/wdtt /usr/bin/qwdtt-client /usr/sbin/wdtt-genlists /usr/sbin/wdtt-resolve 2>/dev/null || true
				rm -rf /etc/qwdtt /etc/wdtt /etc/config/wdtt /var/run/tachyon/wdtt /var/run/qwdtt /etc/tachyon/component-backups/wdtt /var/run/tachyon/component-update-checks/wdtt.json 2>/dev/null || true
				;;
			olcrtc)
				killall -9 olcrtc >/dev/null 2>&1 || true
				rm -f /usr/bin/olcrtc 2>/dev/null || true
				rm -rf /etc/olcrtc /etc/config/olcrtc /var/run/tachyon/olcrtc /etc/tachyon/component-backups/olcrtc /var/run/tachyon/component-update-checks/olcrtc.json 2>/dev/null || true
				;;
		esac
	fi
done

TACHYON_LIB=/usr/lib/tachyon ucode -L /usr/lib/tachyon /usr/lib/tachyon/config/migration.uc migrate

/etc/init.d/tachyon enable >/dev/null 2>&1 || true
/usr/bin/tachyon package_postinst >/dev/null 2>&1 || true
# rpcd caches ACLs, so without this reload the policy shipped in this package
# stays inert until rpcd picks it up, and the stricter read role would look
# applied while the old one kept serving.
[ -x /etc/init.d/rpcd ] && /etc/init.d/rpcd reload >/dev/null 2>&1 || true
chmod 600 /etc/config/tachyon 2>/dev/null || true
chown root:root /etc/config/tachyon 2>/dev/null || true
if [ -d /www/cgi-bin ]; then
	if [ -n "$(uci -q get tachyon.settings.agent_api_token)" ]; then
		ln -sf /usr/lib/cgi-bin/tachyon-agent /www/cgi-bin/tachyon-agent 2>/dev/null || true
	else
		rm -f /www/cgi-bin/tachyon-agent 2>/dev/null || true
	fi
fi

for _f in /www/luci-static/resources/view/tachyon/*.js; do [ -f "$_f" ] && touch "$_f" 2>/dev/null || true; done
[ -f /www/luci-static/resources/luci.js ] && touch /www/luci-static/resources/luci.js 2>/dev/null || true; [ -d /www/luci-static/resources/view/tachyon ] && touch /www/luci-static/resources/view/tachyon 2>/dev/null || true; [ -d /www/luci-static/resources ] && touch /www/luci-static/resources 2>/dev/null || true

# Neutralize legacy unshielded postrm scripts on disk if upgrading from 1.3.21/1.3.22
for p in /usr/lib/opkg/info/tachyon.postrm /usr/lib/opkg/info/luci-app-tachyon.postrm /usr/lib/opkg/info/luci-i18n-tachyon-ru.postrm; do
	if [ -f "$p" ] && ! grep -q '\[ "$1" = "upgrade" \]' "$p"; then
		sed -i '2i[ "$1" = "upgrade" ] && exit 0' "$p" 2>/dev/null || true
	fi
done
exit 0
EOF

  cat > "$control_dir/prerm" <<'EOF'
#!/usr/bin/ucode

// Bounded from the outside like every other prerm here: the cleanup being invoked
// is the OLD installed one, so it cannot be trusted to bound itself.
if (getenv("IPKG_INSTROOT") == null || getenv("IPKG_INSTROOT") == "") {
	let prefix = "";
	if (system("timeout 1 /bin/true >/dev/null 2>&1") == 0)
		prefix = "timeout 90 ";
	else if (system("timeout -t 1 /bin/true >/dev/null 2>&1") == 0)
		prefix = "timeout -t 90 ";

	let action = (length(ARGV) > 0 && ARGV[0] != null && ARGV[0] != "") ? ARGV[0] : "upgrade";
	system(prefix + "/usr/bin/tachyon package_prerm " + action + " >/dev/null 2>&1");
}

exit(0);
EOF

  cat > "$control_dir/postrm" <<'EOF'
#!/bin/sh
[ -n "${IPKG_INSTROOT}" ] && exit 0
[ "$1" = "upgrade" ] && exit 0
[ -x /usr/bin/tachyon ] && exit 0
if [ "$1" != "remove" ] && [ "$1" != "purge" ]; then
    exit 0
fi
if [ -e /var/run/tachyon/component-action.lock ] || [ -e /tmp/run/tachyon/component-action.lock ] || [ -e /var/run/tachyon/component-actions/action.lock ] || [ -e /tmp/run/tachyon/component-actions/action.lock ]; then
    exit 0
fi
rm -f /www/cgi-bin/tachyon-agent /etc/hotplug.d/iface/99-tachyon-wan-monitor 2>/dev/null || true
rm -f /usr/share/nftables.d/chain-pre/input/10-tachyon.nft 2>/dev/null || true
rm -f /usr/share/nftables.d/ruleset-post/90-tachyon-kill-switch.nft 2>/dev/null || true
nft delete table inet TachyonKillSwitch >/dev/null 2>&1 || true
for pref in 9499 9500 9501; do for fam in -4 -6; do while ip $fam rule del pref $pref >/dev/null 2>&1; do :; done; done; done
rm -rf /tmp/ai_doctor* /tmp/tg_* /tmp/warp_* 2>/dev/null || true
rm -rf /var/run/tachyon/section-cache /var/run/tachyon/ui-state 2>/dev/null || true
[ -x /etc/init.d/firewall ] && /etc/init.d/firewall restart >/dev/null 2>&1 || true
[ -x /etc/init.d/dnsmasq ] && /etc/init.d/dnsmasq restart >/dev/null 2>&1 || true
exit 0
EOF

  chmod 0755 "$control_dir/postinst" "$control_dir/prerm" "$control_dir/postrm"
}

write_app_ipk_control() {
  local control_dir="$1"
  local installed_size="$2"

  rm -rf "$control_dir"
  make_dir "$control_dir"

  cat > "$control_dir/control" <<EOF
Package: luci-app-tachyon
Version: ${RELEASE_VERSION}
Depends: ${APP_DEPENDS_IPK}
License: GPL-2.0-or-later
Section: luci
URL: ${PROJECT_URL}
Maintainer: ${MAINTAINER}
Architecture: all
Installed-Size: ${installed_size}
Description: ${APP_DESCRIPTION}
EOF

  cat > "$control_dir/postinst" <<'EOF'
#!/bin/sh
[ "${IPKG_NO_SCRIPT}" = "1" ] && exit 0
[ -s ${IPKG_INSTROOT}/lib/functions.sh ] || exit 0
. ${IPKG_INSTROOT}/lib/functions.sh
default_postinst $0 $@
for _f in /www/luci-static/resources/view/tachyon/*.js; do [ -f "$_f" ] && touch "$_f" 2>/dev/null || true; done
[ -f /www/luci-static/resources/luci.js ] && touch /www/luci-static/resources/luci.js 2>/dev/null || true; [ -d /www/luci-static/resources/view/tachyon ] && touch /www/luci-static/resources/view/tachyon 2>/dev/null || true; [ -d /www/luci-static/resources ] && touch /www/luci-static/resources 2>/dev/null || true
[ -n "${IPKG_INSTROOT}" ] || /usr/bin/tachyon luci_postinst >/dev/null 2>&1 || true
for _f in /www/luci-static/resources/view/tachyon/*.js; do [ -f "$_f" ] && touch "$_f" 2>/dev/null || true; done
[ -f /www/luci-static/resources/luci.js ] && touch /www/luci-static/resources/luci.js 2>/dev/null || true; [ -d /www/luci-static/resources/view/tachyon ] && touch /www/luci-static/resources/view/tachyon 2>/dev/null || true; [ -d /www/luci-static/resources ] && touch /www/luci-static/resources 2>/dev/null || true
EOF

  cat > "$control_dir/postinst-pkg" <<'EOF'
[ -n "${IPKG_INSTROOT}" ] || /usr/bin/tachyon luci_postinst >/dev/null 2>&1 || true
for _f in /www/luci-static/resources/view/tachyon/*.js; do [ -f "$_f" ] && touch "$_f" 2>/dev/null || true; done
[ -f /www/luci-static/resources/luci.js ] && touch /www/luci-static/resources/luci.js 2>/dev/null || true; [ -d /www/luci-static/resources/view/tachyon ] && touch /www/luci-static/resources/view/tachyon 2>/dev/null || true; [ -d /www/luci-static/resources ] && touch /www/luci-static/resources 2>/dev/null || true
EOF

  cat > "$control_dir/prerm" <<'EOF'
#!/bin/sh
[ -s ${IPKG_INSTROOT}/lib/functions.sh ] || exit 0
. ${IPKG_INSTROOT}/lib/functions.sh
default_prerm $0 $@
EOF

  cat > "$control_dir/postrm" <<'EOF'
#!/bin/sh
[ -n "${IPKG_INSTROOT}" ] && exit 0
[ "$1" = "upgrade" ] && exit 0
[ -x /usr/bin/tachyon ] && exit 0
if [ "$1" != "remove" ] && [ "$1" != "purge" ]; then
    exit 0
fi
if [ -e /var/run/tachyon/component-action.lock ] || [ -e /tmp/run/tachyon/component-action.lock ] || [ -e /var/run/tachyon/component-actions/action.lock ] || [ -e /tmp/run/tachyon/component-actions/action.lock ]; then
    exit 0
fi
rm -f /var/luci-indexcache* /tmp/luci-indexcache* /tmp/luci-modulecache/* 2>/dev/null || true
[ -x /etc/init.d/rpcd ] && /etc/init.d/rpcd reload >/dev/null 2>&1 || true
exit 0
EOF

  chmod 0755 "$control_dir/postinst" "$control_dir/prerm" "$control_dir/postrm"
}

write_i18n_ipk_control() {
  local control_dir="$1"
  local installed_size="$2"

  rm -rf "$control_dir"
  make_dir "$control_dir"

  cat > "$control_dir/control" <<EOF
Package: luci-i18n-tachyon-ru
Version: ${RELEASE_VERSION}
Depends: libc, luci-app-tachyon
License: GPL-2.0-or-later
Section: luci
URL: ${PROJECT_URL}
Maintainer: ${MAINTAINER}
Architecture: all
Installed-Size: ${installed_size}
Description: ${I18N_DESCRIPTION}
EOF

  cat > "$control_dir/postinst" <<'EOF'
#!/bin/sh
[ "${IPKG_NO_SCRIPT}" = "1" ] && exit 0
[ -s ${IPKG_INSTROOT}/lib/functions.sh ] || exit 0
. ${IPKG_INSTROOT}/lib/functions.sh
default_postinst $0 $@
EOF

  cat > "$control_dir/prerm" <<'EOF'
#!/bin/sh
[ -s ${IPKG_INSTROOT}/lib/functions.sh ] || exit 0
. ${IPKG_INSTROOT}/lib/functions.sh
default_prerm $0 $@
EOF

  cat > "$control_dir/postrm" <<'EOF'
#!/bin/sh
[ -n "${IPKG_INSTROOT}" ] && exit 0
[ "$1" = "upgrade" ] && exit 0
[ "$1" != "remove" ] && [ "$1" != "purge" ] && [ -n "$1" ] && exit 0
rm -f /var/luci-indexcache* /tmp/luci-indexcache* /tmp/luci-modulecache/* 2>/dev/null || true
[ -x /etc/init.d/rpcd ] && /etc/init.d/rpcd reload >/dev/null 2>&1 || true
exit 0
EOF

  chmod 0755 "$control_dir/postinst" "$control_dir/prerm" "$control_dir/postrm"
}

build_ipk_package() {
  local ipkg_build_bin="$1"
  local package_name="$2"
  local data_root="$3"
  local control_root="$4"
  local output_file="$5"
  local build_dir="$WORK_DIR/manual/ipk-${package_name}"
  local package_root="$build_dir/pkg"
  local built_file

  rm -rf "$build_dir"
  make_dir "$package_root/CONTROL"

  cp -a "$data_root/." "$package_root/"
  cp -a "$control_root/." "$package_root/CONTROL/"

  rm -f "$output_file"
  if [[ "$(id -u)" -eq 0 ]]; then
    chown -R 0:0 "$package_root"
    "$ipkg_build_bin" "$package_root" "$build_dir" >/dev/null
  elif have_passwordless_sudo; then
    sudo chown -R 0:0 "$package_root"
    sudo "$ipkg_build_bin" "$package_root" "$build_dir" >/dev/null
    sudo chown "$(id -u):$(id -g)" "$build_dir/${package_name}_${RELEASE_VERSION}_all.ipk"
  else
    fakeroot sh -c "
      chown -R 0:0 '$package_root'
      '$ipkg_build_bin' '$package_root' '$build_dir' >/dev/null
    "
  fi

  built_file="$build_dir/${package_name}_${RELEASE_VERSION}_all.ipk"
  [ -f "$built_file" ] || {
    echo "Expected IPK artifact not found: $built_file" >&2
    exit 1
  }

  mv "$built_file" "$output_file"
}

write_backend_apk_scripts() {
  local scripts_dir="$1"

  rm -rf "$scripts_dir"
  make_dir "$scripts_dir"

  cat > "$scripts_dir/backend-pre-install.sh" <<'EOF'
#!/usr/bin/ucode
let fs = require("fs");
let cfg = "/etc/config/tachyon";
let backup = "/etc/.tachyon/.cfg-backup.pre-install";
system("mkdir -p /etc/.tachyon 2>/dev/null");
if (fs.stat(cfg)) {
    let data = fs.readfile(cfg);
    if (data != null && data != "")
        fs.writefile(backup, data);
}
exit(0);
EOF

  cat > "$scripts_dir/backend-post-install.sh" <<'EOF'
#!/usr/bin/ucode
let fs = require("fs");
let cfg = "/etc/config/tachyon";
let backup = "/etc/.tachyon/.cfg-backup.pre-install";
function sha256(path) {
    let pipe = fs.popen("sha256sum " + path + " 2>/dev/null", "r");
    if (!pipe) return "";
    let data = pipe.read("all");
    let status = pipe.close();
    if (status != 0 || data == null) return "";
    let parts = split("" + data, /\s+/);
    return parts[0] || "";
}
function restore_cfg_from_backup() {
    if (!fs.stat(backup)) return;
    let backup_hash = sha256(backup);
    let cfg_hash = sha256(cfg);
    if (backup_hash != "" && cfg_hash != "" && backup_hash != cfg_hash) {
        let bk_data = fs.readfile(backup);
        if (bk_data != null && bk_data != "") {
            let tmp = cfg + ".restore-tmp";
            if (fs.writefile(tmp, bk_data) != null) {
                fs.rename(tmp, cfg);
                system("chmod 0600 " + cfg + " 2>/dev/null");
            }
        }
    }
    fs.unlink(backup);
}
if (getenv("IPKG_INSTROOT") == null || getenv("IPKG_INSTROOT") == "") {
    system("/etc/init.d/rpcd reload >/dev/null 2>&1 || true");
    restore_cfg_from_backup();
    system("TACHYON_LIB=/usr/lib/tachyon ucode -L /usr/lib/tachyon /usr/lib/tachyon/config/migration.uc migrate && /etc/init.d/tachyon enable >/dev/null 2>&1 || true; /usr/bin/tachyon package_postinst >/dev/null 2>&1 || true");
    system("for f in /www/luci-static/resources/view/tachyon/*.js; do [ -f \"$f\" ] && touch \"$f\" 2>/dev/null || true; done; [ -f /www/luci-static/resources/luci.js ] && touch /www/luci-static/resources/luci.js 2>/dev/null || true; [ -d /www/luci-static/resources/view/tachyon ] && touch /www/luci-static/resources/view/tachyon 2>/dev/null || true; [ -d /www/luci-static/resources ] && touch /www/luci-static/resources 2>/dev/null || true");
}
exit(0);
EOF

  cat > "$scripts_dir/backend-pre-deinstall.sh" <<'EOF'
#!/usr/bin/ucode

// Bounded for the same reason as backend-pre-upgrade.sh: this runs the OLD
// installed cleanup, and a hook that never returns takes the removal down with it.
if (getenv("IPKG_INSTROOT") == null || getenv("IPKG_INSTROOT") == "") {
	let prefix = "";
	if (system("timeout 1 /bin/true >/dev/null 2>&1") == 0)
		prefix = "timeout 90 ";
	else if (system("timeout -t 1 /bin/true >/dev/null 2>&1") == 0)
		prefix = "timeout -t 90 ";

	system(prefix + "/usr/bin/tachyon package_prerm >/dev/null 2>&1");
}

exit(0);
EOF

  cat > "$scripts_dir/backend-pre-upgrade.sh" <<'EOF'
#!/usr/bin/ucode

// Must mirror Package/tachyon/prerm in tachyon/Makefile: the APK packages are
// assembled here rather than by OpenWrt's packaging, so a fix applied only to the
// Makefile never reaches them.
//
// apk rolls the whole transaction back if this hook fails or outlives its
// patience, which leaves the old build installed. The cleanup invoked below
// belongs to the OLD version, so it cannot be trusted to bound itself — the hook
// bounds it from the outside. BusyBox timeout wanted `-t SECONDS` on older builds
// and rejects it on newer ones; the spelling is probed against /bin/true because
// probing with the real command would run the cleanup twice whenever the first
// form is unsupported.
if (getenv("IPKG_INSTROOT") == null || getenv("IPKG_INSTROOT") == "") {
    let prefix = "";
    if (system("timeout 1 /bin/true >/dev/null 2>&1") == 0)
        prefix = "timeout 90 ";
    else if (system("timeout -t 1 /bin/true >/dev/null 2>&1") == 0)
        prefix = "timeout -t 90 ";

    system(prefix + "/usr/bin/tachyon package_prerm upgrade >/dev/null 2>&1");
}

// Whatever the cleanup managed to do, the upgrade itself must proceed: the old
// `exit(system(...))` form returned a raw wait status, so a killed or merely
// unhappy cleanup aborted the upgrade and rolled the new build back.
exit(0);
EOF

  cat > "$scripts_dir/backend-post-upgrade.sh" <<'EOF'
#!/usr/bin/ucode
let fs = require("fs");
let cfg = "/etc/config/tachyon";
let backup = "/etc/.tachyon/.cfg-backup.pre-install";
function sha256(path) {
    let pipe = fs.popen("sha256sum " + path + " 2>/dev/null", "r");
    if (!pipe) return "";
    let data = pipe.read("all");
    let status = pipe.close();
    if (status != 0 || data == null) return "";
    let parts = split("" + data, /\s+/);
    return parts[0] || "";
}
function restore_cfg_from_backup() {
    if (!fs.stat(backup)) return;
    let backup_hash = sha256(backup);
    let cfg_hash = sha256(cfg);
    if (backup_hash != "" && cfg_hash != "" && backup_hash != cfg_hash) {
        let bk_data = fs.readfile(backup);
        if (bk_data != null && bk_data != "") {
            let tmp = cfg + ".restore-tmp";
            if (fs.writefile(tmp, bk_data) != null) {
                fs.rename(tmp, cfg);
                system("chmod 0600 " + cfg + " 2>/dev/null");
            }
        }
    }
    fs.unlink(backup);
}
if (getenv("IPKG_INSTROOT") == null || getenv("IPKG_INSTROOT") == "") {
    system("/etc/init.d/rpcd reload >/dev/null 2>&1 || true");
    system("if [ -d /www/cgi-bin ]; then if [ -n \"$(uci -q get tachyon.settings.agent_api_token)\" ]; then ln -sf /usr/lib/cgi-bin/tachyon-agent /www/cgi-bin/tachyon-agent 2>/dev/null || true; else rm -f /www/cgi-bin/tachyon-agent 2>/dev/null || true; fi; fi");
    restore_cfg_from_backup();
    system("TACHYON_LIB=/usr/lib/tachyon ucode -L /usr/lib/tachyon /usr/lib/tachyon/config/migration.uc migrate && /etc/init.d/tachyon enable >/dev/null 2>&1 || true; /usr/bin/tachyon package_postinst >/dev/null 2>&1 || true");
    system("for f in /www/luci-static/resources/view/tachyon/*.js; do [ -f \"$f\" ] && touch \"$f\" 2>/dev/null || true; done; [ -f /www/luci-static/resources/luci.js ] && touch /www/luci-static/resources/luci.js 2>/dev/null || true; [ -d /www/luci-static/resources/view/tachyon ] && touch /www/luci-static/resources/view/tachyon 2>/dev/null || true; [ -d /www/luci-static/resources ] && touch /www/luci-static/resources 2>/dev/null || true");
}
exit(0);
EOF

  cat > "$scripts_dir/backend-post-deinstall.sh" <<'EOF'
#!/bin/sh
[ -n "${IPKG_INSTROOT}" ] && exit 0
[ -x /usr/bin/tachyon ] && exit 0
if [ -e /var/run/tachyon/component-action.lock ] || [ -e /tmp/run/tachyon/component-action.lock ] || [ -e /var/run/tachyon/component-actions/action.lock ] || [ -e /tmp/run/tachyon/component-actions/action.lock ]; then
    exit 0
fi
rm -f /www/cgi-bin/tachyon-agent /etc/hotplug.d/iface/99-tachyon-wan-monitor 2>/dev/null || true
rm -f /usr/share/nftables.d/chain-pre/input/10-tachyon.nft 2>/dev/null || true
rm -f /usr/share/nftables.d/ruleset-post/90-tachyon-kill-switch.nft 2>/dev/null || true
nft delete table inet TachyonKillSwitch >/dev/null 2>&1 || true
for pref in 9499 9500 9501; do for fam in -4 -6; do while ip $fam rule del pref $pref >/dev/null 2>&1; do :; done; done; done
rm -rf /tmp/ai_doctor* /tmp/tg_* /tmp/warp_* 2>/dev/null || true
rm -rf /var/run/tachyon/section-cache /var/run/tachyon/ui-state 2>/dev/null || true
[ -x /etc/init.d/firewall ] && /etc/init.d/firewall restart >/dev/null 2>&1 || true
[ -x /etc/init.d/dnsmasq ] && /etc/init.d/dnsmasq restart >/dev/null 2>&1 || true
exit 0
EOF

  chmod 0755 "$scripts_dir"/backend-*.sh
}

write_app_apk_scripts() {
  local scripts_dir="$1"

  make_dir "$scripts_dir"

  cat > "$scripts_dir/app-pre-install.sh" <<'EOF'
#!/bin/sh
mkdir -p /www/luci-static/resources/view/tachyon/fonts 2>/dev/null || true
exit 0
EOF

  cat > "$scripts_dir/app-post-install.sh" <<'EOF'
#!/bin/sh
[ "${IPKG_NO_SCRIPT}" = "1" ] && exit 0
[ -s ${IPKG_INSTROOT}/lib/functions.sh ] || exit 0
. ${IPKG_INSTROOT}/lib/functions.sh
export root="${IPKG_INSTROOT}"
export pkgname="luci-app-tachyon"
add_group_and_user
default_postinst
[ -n "${IPKG_INSTROOT}" ] || /usr/bin/tachyon luci_postinst >/dev/null 2>&1 || true
for _f in /www/luci-static/resources/view/tachyon/*.js; do [ -f "$_f" ] && touch "$_f" 2>/dev/null || true; done
[ -f /www/luci-static/resources/luci.js ] && touch /www/luci-static/resources/luci.js 2>/dev/null || true; [ -d /www/luci-static/resources/view/tachyon ] && touch /www/luci-static/resources/view/tachyon 2>/dev/null || true; [ -d /www/luci-static/resources ] && touch /www/luci-static/resources 2>/dev/null || true
EOF

  cat > "$scripts_dir/app-pre-deinstall.sh" <<'EOF'
#!/bin/sh
[ -s ${IPKG_INSTROOT}/lib/functions.sh ] || exit 0
. ${IPKG_INSTROOT}/lib/functions.sh
export root="${IPKG_INSTROOT}"
export pkgname="luci-app-tachyon"
default_prerm
exit 0
EOF

  cat > "$scripts_dir/app-pre-upgrade.sh" <<'EOF'
#!/bin/sh
exit 0
EOF

  cat > "$scripts_dir/app-post-upgrade.sh" <<'EOF'
#!/bin/sh
export PKG_UPGRADE=1
[ "${IPKG_NO_SCRIPT}" = "1" ] && exit 0
[ -s ${IPKG_INSTROOT}/lib/functions.sh ] || exit 0
. ${IPKG_INSTROOT}/lib/functions.sh
export root="${IPKG_INSTROOT}"
export pkgname="luci-app-tachyon"
add_group_and_user
default_postinst
[ -n "${IPKG_INSTROOT}" ] || /usr/bin/tachyon luci_postinst >/dev/null 2>&1 || true
for _f in /www/luci-static/resources/view/tachyon/*.js; do [ -f "$_f" ] && touch "$_f" 2>/dev/null || true; done
[ -f /www/luci-static/resources/luci.js ] && touch /www/luci-static/resources/luci.js 2>/dev/null || true; [ -d /www/luci-static/resources/view/tachyon ] && touch /www/luci-static/resources/view/tachyon 2>/dev/null || true; [ -d /www/luci-static/resources ] && touch /www/luci-static/resources 2>/dev/null || true
EOF

  cat > "$scripts_dir/app-post-deinstall.sh" <<'EOF'
#!/bin/sh
[ -n "${IPKG_INSTROOT}" ] && exit 0
[ -f /usr/share/luci/menu.d/luci-app-tachyon.json ] && exit 0
rm -f /var/luci-indexcache* /var/luci-modulecache* 2>/dev/null || true
rm -f /tmp/luci-* 2>/dev/null || true
[ -x /etc/init.d/rpcd ] && /etc/init.d/rpcd reload >/dev/null 2>&1 || true
exit 0
EOF

  chmod 0755 "$scripts_dir"/app-*.sh
}

write_i18n_apk_scripts() {
  local scripts_dir="$1"

  make_dir "$scripts_dir"

  cat > "$scripts_dir/i18n-pre-install.sh" <<'EOF'
#!/bin/sh
exit 0
EOF

  cat > "$scripts_dir/i18n-post-install.sh" <<'EOF'
#!/bin/sh
[ "${IPKG_NO_SCRIPT}" = "1" ] && exit 0
[ -s ${IPKG_INSTROOT}/lib/functions.sh ] || exit 0
. ${IPKG_INSTROOT}/lib/functions.sh
export root="${IPKG_INSTROOT}"
export pkgname="luci-i18n-tachyon-ru"
add_group_and_user
default_postinst
EOF

  cat > "$scripts_dir/i18n-pre-deinstall.sh" <<'EOF'
#!/bin/sh
[ -s ${IPKG_INSTROOT}/lib/functions.sh ] || exit 0
. ${IPKG_INSTROOT}/lib/functions.sh
export root="${IPKG_INSTROOT}"
export pkgname="luci-i18n-tachyon-ru"
default_prerm
EOF

  cat > "$scripts_dir/i18n-pre-upgrade.sh" <<'EOF'
#!/bin/sh
exit 0
EOF

  cat > "$scripts_dir/i18n-post-upgrade.sh" <<'EOF'
#!/bin/sh
export PKG_UPGRADE=1
[ "${IPKG_NO_SCRIPT}" = "1" ] && exit 0
[ -s ${IPKG_INSTROOT}/lib/functions.sh ] || exit 0
. ${IPKG_INSTROOT}/lib/functions.sh
export root="${IPKG_INSTROOT}"
export pkgname="luci-i18n-tachyon-ru"
add_group_and_user
default_postinst
EOF

  cat > "$scripts_dir/i18n-post-deinstall.sh" <<'EOF'
#!/bin/sh
exit 0
EOF

  chmod 0755 "$scripts_dir"/i18n-*.sh
}

build_apk_package() {
  local apk_bin="$1"
  local package_name="$2"
  local package_version="$3"
  local description="$4"
  local depends="$5"
  local files_root="$6"
  local scripts_dir="$7"
  local script_prefix="$8"
  local output_file="$9"
  local temp_root="$WORK_DIR/manual/${package_name}.apk-root"
  local temp_scripts="$WORK_DIR/manual/${package_name}.apk-scripts"
  local maintainer="${10}"
  local stderr_file

  local extra_args=()

  rm -rf "$temp_root" "$temp_scripts"
  cp -a "$files_root" "$temp_root"
  cp -a "$scripts_dir" "$temp_scripts"

  if [[ "$(id -u)" -eq 0 ]]; then
    chown -R 0:0 "$temp_root" "$temp_scripts"
    "$apk_bin" mkpkg \
      --files "$temp_root" \
      --output "$output_file" \
      -I "name:${package_name}" \
      -I "version:${package_version}" \
      -I "description:${description}" \
      -I "arch:noarch" \
      -I "license:GPL-2.0-or-later" \
      -I "origin:tachyon" \
      -I "maintainer:${maintainer}" \
      -I "url:${PROJECT_URL}" \
      -I "depends:${depends}" \
      "${extra_args[@]}" \
      -s "pre-install:${temp_scripts}/${script_prefix}-pre-install.sh" \
      -s "post-install:${temp_scripts}/${script_prefix}-post-install.sh" \
      -s "pre-deinstall:${temp_scripts}/${script_prefix}-pre-deinstall.sh" \
      -s "post-deinstall:${temp_scripts}/${script_prefix}-post-deinstall.sh" \
      -s "pre-upgrade:${temp_scripts}/${script_prefix}-pre-upgrade.sh" \
      -s "post-upgrade:${temp_scripts}/${script_prefix}-post-upgrade.sh"
  elif have_passwordless_sudo; then
    sudo chown -R 0:0 "$temp_root" "$temp_scripts"
    sudo "$apk_bin" mkpkg \
      --files "$temp_root" \
      --output "$output_file" \
      -I "name:${package_name}" \
      -I "version:${package_version}" \
      -I "description:${description}" \
      -I "arch:noarch" \
      -I "license:GPL-2.0-or-later" \
      -I "origin:tachyon" \
      -I "maintainer:${maintainer}" \
      -I "url:${PROJECT_URL}" \
      -I "depends:${depends}" \
      "${extra_args[@]}" \
      -s "pre-install:${temp_scripts}/${script_prefix}-pre-install.sh" \
      -s "post-install:${temp_scripts}/${script_prefix}-post-install.sh" \
      -s "pre-deinstall:${temp_scripts}/${script_prefix}-pre-deinstall.sh" \
      -s "post-deinstall:${temp_scripts}/${script_prefix}-post-deinstall.sh" \
      -s "pre-upgrade:${temp_scripts}/${script_prefix}-pre-upgrade.sh" \
      -s "post-upgrade:${temp_scripts}/${script_prefix}-post-upgrade.sh"
    sudo chown "$(id -u):$(id -g)" "$output_file"
    sudo rm -rf "$temp_root" "$temp_scripts"
  elif have_unshare_root; then
    # shellcheck disable=SC2048,SC2086
    unshare -r sh -c "
      chown -R 0:0 '$temp_root' '$temp_scripts'
      '$apk_bin' mkpkg \
        --files '$temp_root' \
        --output '$output_file' \
        -I 'name:${package_name}' \
        -I 'version:${package_version}' \
        -I 'description:${description}' \
        -I 'arch:noarch' \
        -I 'license:GPL-2.0-or-later' \
        -I 'origin:tachyon' \
        -I 'maintainer:${maintainer}' \
        -I 'url:${PROJECT_URL}' \
        -I 'depends:${depends}' \
        ${extra_args[*]} \
        -s pre-install:'$temp_scripts/${script_prefix}-pre-install.sh' \
        -s post-install:'$temp_scripts/${script_prefix}-post-install.sh' \
        -s pre-deinstall:'$temp_scripts/${script_prefix}-pre-deinstall.sh' \
        -s post-deinstall:'$temp_scripts/${script_prefix}-post-deinstall.sh' \
        -s pre-upgrade:'$temp_scripts/${script_prefix}-pre-upgrade.sh' \
        -s post-upgrade:'$temp_scripts/${script_prefix}-post-upgrade.sh'
    "
  else
    stderr_file="$(mktemp)"
    # shellcheck disable=SC2048,SC2086
    if ! fakeroot sh -c "
      chown -R 0:0 '$temp_root' '$temp_scripts'
      '$apk_bin' mkpkg \
        --files '$temp_root' \
        --output '$output_file' \
        -I 'name:${package_name}' \
        -I 'version:${package_version}' \
        -I 'description:${description}' \
        -I 'arch:noarch' \
        -I 'license:GPL-2.0-or-later' \
        -I 'origin:tachyon' \
        -I 'maintainer:${maintainer}' \
        -I 'url:${PROJECT_URL}' \
        -I 'depends:${depends}' \
        ${extra_args[*]} \
        -s pre-install:'$temp_scripts/${script_prefix}-pre-install.sh' \
        -s post-install:'$temp_scripts/${script_prefix}-post-install.sh' \
        -s pre-deinstall:'$temp_scripts/${script_prefix}-pre-deinstall.sh' \
        -s post-deinstall:'$temp_scripts/${script_prefix}-post-deinstall.sh' \
        -s pre-upgrade:'$temp_scripts/${script_prefix}-pre-upgrade.sh' \
        -s post-upgrade:'$temp_scripts/${script_prefix}-post-upgrade.sh'
    " 2>"$stderr_file"; then
      grep -v "object 'libfakeroot-.*so' from LD_PRELOAD cannot be preloaded" "$stderr_file" >&2 || true
      rm -f "$stderr_file"
      return 1
    fi
    grep -v "object 'libfakeroot-.*so' from LD_PRELOAD cannot be preloaded" "$stderr_file" >&2 || true
    rm -f "$stderr_file"
  fi
}

verify_ipk_metadata() {
  local package_file="$1"
  local expected_package="$2"
  local expected_version="$3"
  local tmp_dir

  tmp_dir="$(mktemp -d)"
  tar -xzf "$package_file" -C "$tmp_dir"
  tar -xzf "$tmp_dir/control.tar.gz" -C "$tmp_dir"
  grep -q "^Package: ${expected_package}$" "$tmp_dir/control"
  grep -q "^Version: ${expected_version}$" "$tmp_dir/control"
  rm -rf "$tmp_dir"
}

verify_apk_metadata() {
  local apk_bin="$1"
  local package_file="$2"
  local expected_package="$3"
  local expected_version="$4"
  local dump_file

  dump_file="$(mktemp)"
  "$apk_bin" adbdump "$package_file" > "$dump_file"
  grep -q "^  name: ${expected_package}$" "$dump_file"
  grep -q "^  version: ${expected_version}$" "$dump_file"
  rm -f "$dump_file"
}

cleanup_work_dir() {
  rm -rf "$WORK_DIR/manual" 2>/dev/null || {
    if have_passwordless_sudo; then
      sudo rm -rf "$WORK_DIR/manual"
    else
      return 1
    fi
  }

  rm -f "$WORK_DIR/ipk-build.log" 2>/dev/null || {
    if have_passwordless_sudo; then
      sudo rm -f "$WORK_DIR/ipk-build.log"
    else
      return 1
    fi
  }
}

sync_artifacts_to_windows() {
  local output_dir="$1"
  local output_real
  local windows_real

  [[ -n "$WINDOWS_ARTIFACTS_DIR" ]] || return 0

  mkdir -p "$WINDOWS_ARTIFACTS_DIR"
  output_real="$(readlink -f "$output_dir")"
  windows_real="$(readlink -f "$WINDOWS_ARTIFACTS_DIR")"

  if [[ "$output_real" == "$windows_real" ]]; then
    return 0
  fi

  rm -f \
    "$WINDOWS_ARTIFACTS_DIR"/tachyon_* \
    "$WINDOWS_ARTIFACTS_DIR"/luci-app-tachyon_* \
    "$WINDOWS_ARTIFACTS_DIR"/luci-i18n-tachyon-ru_* \
    "$WINDOWS_ARTIFACTS_DIR"/sha256sums*

  cp -f \
    "$output_dir"/tachyon_"${RELEASE_VERSION}".ipk \
    "$output_dir"/luci-app-tachyon_"${RELEASE_VERSION}".ipk \
    "$output_dir"/luci-i18n-tachyon-ru_"${RELEASE_VERSION}".ipk \
    "$output_dir"/tachyon_"${RELEASE_VERSION}".apk \
    "$output_dir"/luci-app-tachyon_"${RELEASE_VERSION}".apk \
    "$output_dir"/luci-i18n-tachyon-ru_"${RELEASE_VERSION}".apk \
    "$WINDOWS_ARTIFACTS_DIR"/

  if [ -f "$output_dir/sha256sums.txt" ]; then
    cp -f "$output_dir/sha256sums.txt" "$WINDOWS_ARTIFACTS_DIR/"
  fi
  echo "Synced artifacts to Windows path: $WINDOWS_ARTIFACTS_DIR" >&2
}

print_summary() {
  local output_dir="$1"

  echo "Build root: $ROOT_DIR"
  echo "Output dir: $output_dir"
  if [[ -n "$WINDOWS_ARTIFACTS_DIR" ]]; then
    echo "Windows artifacts dir: $WINDOWS_ARTIFACTS_DIR"
  fi
  echo "Artifacts:"
  find "$output_dir" -maxdepth 1 -type f \( -name '*.ipk' -o -name '*.apk' -o -name 'sha256sums*' \) | sort
}

main() {
  local output_dir
  local host_tools_dir
  local po2lmo_bin
  local ipkg_build_bin
  local apk_bin
  local manual_root="$WORK_DIR/manual"
  local backend_root="$manual_root/backend-root"
  local app_root="$manual_root/app-root"
  local i18n_root="$manual_root/i18n-root"
  local backend_control="$manual_root/backend-ipk-control"
  local app_control="$manual_root/app-ipk-control"
  local i18n_control="$manual_root/i18n-ipk-control"
  local apk_scripts="$manual_root/apk-scripts"
  local backend_size
  local app_size
  local i18n_size

  ensure_native_root
  ensure_host_deps

  mkdir -p "$WORK_DIR"
  output_dir="${OUTPUT_DIR_INPUT:-$ROOT_DIR/dist/release-final}"
  mkdir -p "$output_dir"
  rm -f "$output_dir"/tachyon_* "$output_dir"/luci-app-tachyon_* "$output_dir"/luci-i18n-tachyon-ru_*

  host_tools_dir="$(ensure_host_tools)"
  po2lmo_bin="$host_tools_dir/bin/po2lmo"
  ipkg_build_bin="$host_tools_dir/bin/ipkg-build"
  apk_bin="$host_tools_dir/bin/apk"
  [[ -x "$po2lmo_bin" ]] || { echo "po2lmo not found at $po2lmo_bin" >&2; exit 1; }
  [[ -x "$ipkg_build_bin" ]] || { echo "ipkg-build not found at $ipkg_build_bin" >&2; exit 1; }
  [[ -x "$apk_bin" ]] || { echo "apk host tool not found at $apk_bin" >&2; exit 1; }

  echo "Building RAG index..." >&2
  bash "$ROOT_DIR/tools/rag_build_index.sh" "$ROOT_DIR/docs/knowledge-base" "$ROOT_DIR/tachyon/files/usr/lib" || true

  build_backend_root "$backend_root"
  build_app_root "$app_root"
  build_i18n_root "$i18n_root" "$po2lmo_bin"

  backend_size="$(installed_size_bytes "$backend_root")"
  app_size="$(installed_size_bytes "$app_root")"
  i18n_size="$(installed_size_bytes "$i18n_root")"

  write_backend_ipk_control "$backend_control" "$backend_size"
  write_app_ipk_control "$app_control" "$app_size"
  write_i18n_ipk_control "$i18n_control" "$i18n_size"

  build_ipk_package \
    "$ipkg_build_bin" \
    "tachyon" \
    "$backend_root" \
    "$backend_control" \
    "$output_dir/tachyon_${RELEASE_VERSION}.ipk"

  build_ipk_package \
    "$ipkg_build_bin" \
    "luci-app-tachyon" \
    "$app_root" \
    "$app_control" \
    "$output_dir/luci-app-tachyon_${RELEASE_VERSION}.ipk"

  build_ipk_package \
    "$ipkg_build_bin" \
    "luci-i18n-tachyon-ru" \
    "$i18n_root" \
    "$i18n_control" \
    "$output_dir/luci-i18n-tachyon-ru_${RELEASE_VERSION}.ipk"

  generate_apk_metadata_files "tachyon" "$backend_root" "/etc/config/tachyon"
  generate_apk_metadata_files "luci-app-tachyon" "$app_root"
  generate_apk_metadata_files "luci-i18n-tachyon-ru" "$i18n_root"
  write_backend_apk_scripts "$apk_scripts"
  write_app_apk_scripts "$apk_scripts"
  write_i18n_apk_scripts "$apk_scripts"

  build_apk_package \
    "$apk_bin" \
    "tachyon" \
    "$APK_INTERNAL_VERSION" \
    "$BACKEND_DESCRIPTION" \
    "$BACKEND_DEPENDS_APK" \
    "$backend_root" \
    "$apk_scripts" \
    "backend" \
    "$output_dir/tachyon_${RELEASE_VERSION}.apk" \
    "$MAINTAINER"

  build_apk_package \
    "$apk_bin" \
    "luci-app-tachyon" \
    "$APK_INTERNAL_VERSION" \
    "$APP_DESCRIPTION" \
    "$APP_DEPENDS_APK" \
    "$app_root" \
    "$apk_scripts" \
    "app" \
    "$output_dir/luci-app-tachyon_${RELEASE_VERSION}.apk" \
    "$MAINTAINER"

  build_apk_package \
    "$apk_bin" \
    "luci-i18n-tachyon-ru" \
    "$APK_INTERNAL_VERSION" \
    "$I18N_DESCRIPTION" \
    "libc luci-app-tachyon" \
    "$i18n_root" \
    "$apk_scripts" \
    "i18n" \
    "$output_dir/luci-i18n-tachyon-ru_${RELEASE_VERSION}.apk" \
    "$MAINTAINER"

  verify_ipk_metadata "$output_dir/tachyon_${RELEASE_VERSION}.ipk" "tachyon" "$RELEASE_VERSION"
  verify_ipk_metadata "$output_dir/luci-app-tachyon_${RELEASE_VERSION}.ipk" "luci-app-tachyon" "$RELEASE_VERSION"
  verify_ipk_metadata "$output_dir/luci-i18n-tachyon-ru_${RELEASE_VERSION}.ipk" "luci-i18n-tachyon-ru" "$RELEASE_VERSION"
  verify_apk_metadata "$apk_bin" "$output_dir/tachyon_${RELEASE_VERSION}.apk" "tachyon" "$APK_INTERNAL_VERSION"
  verify_apk_metadata "$apk_bin" "$output_dir/luci-app-tachyon_${RELEASE_VERSION}.apk" "luci-app-tachyon" "$APK_INTERNAL_VERSION"
  verify_apk_metadata "$apk_bin" "$output_dir/luci-i18n-tachyon-ru_${RELEASE_VERSION}.apk" "luci-i18n-tachyon-ru" "$APK_INTERNAL_VERSION"

  (
    cd "$output_dir" || exit 1
    rm -f sha256sums.txt
    for f in *; do
      if [ -f "$f" ]; then
        sha256sum "$f" >> sha256sums.txt
      fi
    done
  )


  cleanup_work_dir
  sync_artifacts_to_windows "$output_dir"
  print_summary "$output_dir"
}

# Sourced so tests can call build_backend_root and inspect the staged package
# tree without paying for the SDK, the frontend build and the archives. The
# release artifacts are assembled here, and the package contents were once wrong
# in three ways that no source-level test could see, so the staged tree itself
# is the thing worth asserting on.
if [ "${BASH_SOURCE[0]}" = "$0" ]; then
  main "$@"
fi
