#! /usr/bin/env nix-shell
#! nix-shell -i bash --pure -p nix curl cacert gzip

set -euo pipefail

cd "$(dirname "$(readlink -f "$0")")"

base_url_suffix="https://pro-store-packages.uniontech.com/appstore/dists/eagle/appstore/binary-"
base_url_appendix="/Packages.gz"
target_package="com.xunlei.download"
packages_file="Packages.gz"

url=()
version=()  # TODO: Currently, there is no version differences between archs. This is reserved for future use.
hash=()

for i in amd64 arm64 loongarch64
do
    current_url=$base_url_suffix$i$base_url_appendix
    curl -A "Mozilla/5.0 (X11; Linux x86_64; rv:125.0) Gecko/20100101 Firefox/125.0" -v -L -O $current_url
    current_version=$(zgrep -A 20 "Package: $target_package" "$packages_file" | awk -v pkg="$target_package" '
    BEGIN { found = 0 }
    {
        if ($0 ~ "^Package: "pkg) {
            found = 1;
        }
        if (found && $1 == "Version:") {
            print $2;
            exit;
        }
    }
    ')
    version+=("$current_version")
    sha256sum=$(zgrep -A 20 "Package: $target_package" "$packages_file" | awk -v pkg="$target_package" '
    BEGIN { found = 0 }
        {
            if ($0 ~ "^Package: "pkg) {
            found = 1;
        }
        if (found && $1 == "SHA256:") {
            print $2;
            exit;
        }
    }
    ')
    url+=("https://archive2.kylinos.cn/DEB/KYLIN_DEB/pool/all/com.xunlei.download_"$version"_"$i".deb")
    hash+=("$(nix --extra-experimental-features nix-command hash convert --to sri --hash-algo sha256 "$(nix-prefetch-url "${url[-1]}")")")
done

cat >sources.nix <<EOF
# Generated by ./update.sh - do not update manually!
# Last updated: $(date +%F)
{
  version = "${version[0]}";
  amd64_url = "${url[0]}";
  arm64_url = "${url[1]}";
  loongarch64_url = "${url[2]}";
  amd64_hash = "${hash[0]}";
  arm64_hash = "${hash[1]}";
  loongarch64_hash = "${hash[2]}";
}
EOF

rm -r Packages.gz
