#!/bin/sh
# Offline-first list cache. Does not change routing, DNS, Tachyon or NodeWatch.
set -eu
umask 077
root=${PUPS_LIST_ROOT:-/etc/pupsinator/lists}
helper=${PUPS_LIST_HELPER:-/usr/lib/pupsinator/lists.uc}
download_proxy=${PUPS_DOWNLOAD_PROXY:-$(cat /etc/pupsinator/list-download-proxy 2>/dev/null || true)}
lock=/tmp/pupsinator-lists.lock
max_kib=${PUPS_LIST_LIMIT_KIB:-24576}
raw=https://raw.githubusercontent.com/Dushnilin/tachyon-lists
action=${1:-status}
case "$action" in
status) exec ucode "$helper" status "$root" ;;
update|preload) ;;
*) echo 'Usage: pupsinator-lists status | update | preload [all|id ...]' >&2; exit 2 ;;
esac
mkdir -p "$root/generations"
if ! mkdir "$lock" 2>/dev/null; then echo 'List update already running' >&2; exit 1; fi
stage=''
cleanup() { code=$?; [ -z "$stage" ] || rm -rf "$stage"; rm -f "$root/current.new"; rmdir "$lock"; if [ "$code" -ne 0 ]; then echo 'Update failed; last working cache retained' > "$root/last-error"; fi; }
trap cleanup EXIT
trap 'exit 130' INT TERM HUP
date -u '+%Y-%m-%dT%H:%M:%SZ' > "$root/last-attempt"
ids=''
if [ "$action" = preload ]; then shift; ids="$*"; fi
if [ -z "$ids" ]; then ids=$(cat "$root/selected" 2>/dev/null || true); fi
[ -n "$ids" ] || { echo 'Select lists before update' >&2; exit 2; }
# Untrusted ids are parsed by helper; never interpolated into commands.
stage=$(mktemp -d "$root/generations/gen-XXXXXXXX")
curl_safe() {
    if [ -n "$download_proxy" ]; then
        echo 'List download: VPN first' >&2
        if curl --proxy "$download_proxy" --proto '=https' --proto-redir '=https' -fLsS --connect-timeout 7 --max-time 45 --retry 1 --max-filesize 8388608 -o "$2" "$1"; then return 0; fi
        echo 'VPN download failed; trying direct fallback, keeping current cache until complete' >&2
    fi
    curl --proto '=https' --proto-redir '=https' -fLsS --connect-timeout 10 --max-time 45 --retry 2 --max-filesize 8388608 -o "$2" "$1"
}
curl_safe https://api.github.com/repos/Dushnilin/tachyon-lists/commits/main "$stage/commit.json"
revision=$(ucode "$helper" commit "$stage/commit.json")
curl_safe "$raw/$revision/release/catalog.json" "$stage/upstream-catalog.json"
ucode "$helper" augment "$stage/upstream-catalog.json" "$stage/catalog.json" "${PUPS_SETTINGS_FILE:-/etc/pupsinator/settings.json}"
ucode "$helper" plan "$stage/catalog.json" "$ids" > "$stage/plan.tsv"
[ -s "$stage/plan.tsv" ]
mkdir -p "$stage/source" "$stage/xray" "$stage/subnets"
if [ -s "$root/current/SHA256SUMS" ]; then (cd "$root/current"; sha256sum -c SHA256SUMS >/dev/null); fi
total=0
mobile_revision=''
tab=$(printf '\t')
while IFS="$tab" read -r id path subnet custom_url custom_format; do
    # Reuse identical immutable revision without a network request.
    if [ "$custom_url" != - ]; then
        curl_safe "$custom_url" "$stage/custom-input"
        [ "$(wc -c < "$stage/custom-input")" -le 2097152 ] || { echo 'Custom source exceeds 2 MiB' >&2; exit 1; }
        if [ "$custom_format" = json ]; then cp "$stage/custom-input" "$stage/source/$id.json";
        else ucode "$helper" plain "$stage/custom-input" "$stage/source/$id.json" "$custom_format"; fi
        rm -f "$stage/custom-input"
    elif [ "$id" = mobile_whitelist ] || [ "$id" = mobile_whitelist_ip ]; then
        if [ -z "$mobile_revision" ]; then
            curl_safe https://api.github.com/repos/hxehex/russia-mobile-internet-whitelist/commits/main "$stage/mobile-commit.json"
            mobile_revision=$(ucode "$helper" commit "$stage/mobile-commit.json")
            echo "$mobile_revision" > "$stage/mobile-revision"
        fi
        curl_safe "https://raw.githubusercontent.com/hxehex/russia-mobile-internet-whitelist/$mobile_revision/${path#external/}" "$stage/plain.txt"
        kind=domains; [ "$id" != mobile_whitelist_ip ] || kind=cidrs
        ucode "$helper" plain "$stage/plain.txt" "$stage/source/$id.json" "$kind"
        rm -f "$stage/plain.txt"
    elif [ "$(cat "$root/current/revision" 2>/dev/null || true)" = "$revision" ] && { [ -s "$root/current/source/$id.json" ] || [ -s "$root/current/source/$id.json.gz" ]; }; then
        if [ -s "$root/current/source/$id.json.gz" ]; then gzip -dc "$root/current/source/$id.json.gz" > "$stage/source/$id.json"; else cp "$root/current/source/$id.json" "$stage/source/$id.json"; fi
    else
        curl_safe "$raw/$revision/$path" "$stage/source/$id.json"
    fi
    compile_source="$stage/source/$id.json"
    if [ "$subnet" != - ]; then
        if [ "$(cat "$root/current/revision" 2>/dev/null || true)" = "$revision" ] && [ -s "$root/current/subnets/$id.lst" ]; then
            cp "$root/current/subnets/$id.lst" "$stage/subnets/$id.lst"
        else
            curl_safe "$raw/$revision/$subnet" "$stage/subnets/$id.lst"
        fi
        ucode "$helper" with-subnets "$stage/source/$id.json" "$stage/subnets/$id.lst" "$stage/merged.json"
        compile_source="$stage/merged.json"
    fi
    ucode "$helper" compile "$compile_source" "$stage/xray/$id.json"
    rm -f "$stage/subnets.txt" "$stage/merged.json"
    total=$(du -sk "$stage" | awk '{print $1}')
    [ "$total" -le "$max_kib" ] || { echo 'Cache limit exceeded; select fewer lists or use external storage' >&2; exit 1; }
    available=$(df -Pk "$root" | awk 'END {print $4}')
    [ "$available" -gt 4096 ] || { echo 'Insufficient flash space' >&2; exit 1; }
done < "$stage/plan.tsv"
echo "$revision" > "$stage/revision"
for file in "$stage"/source/*.json "$stage"/xray/*.json; do gzip "$file"; done
rm -f "$stage/commit.json" "$stage/upstream-catalog.json" "$stage/mobile-commit.json"
total=$(du -sk "$stage" | awk '{print $1}')
(cd "$stage"; sha256sum catalog.json source/*.json.gz xray/*.json.gz > SHA256SUMS; for f in subnets/*.lst; do [ ! -f "$f" ] || sha256sum "$f" >> SHA256SUMS; done; sha256sum -c SHA256SUMS >/dev/null)
old=$(readlink "$root/current" 2>/dev/null || true)
ln -s "generations/$(basename "$stage")" "$root/current.new"
# BusyBox mv -T replaces the symlink itself, never follows current into a directory.
mv -Tf "$root/current.new" "$root/current"
stage=''
sync
cut -f1 "$root/current/plan.tsv" > "$root/selected.new"
mv "$root/selected.new" "$root/selected"
date -u '+%Y-%m-%dT%H:%M:%SZ' > "$root/last-success"
rm -f "$root/last-error"
# Keep one previous generation, remove only our verified generation directories.
current=$(readlink "$root/current")
for dir in "$root"/generations/gen-*; do
    [ -d "$dir" ] || continue
    rel="generations/$(basename "$dir")"
    [ "$rel" = "$old" ] || [ "$rel" = "$current" ] || rm -rf "$dir"
done
echo "Lists ready offline: $total KiB; revision $revision"
