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

base_url_suffix="https://pro-store-packages.uniontech.com/appstore/dists/eagle-pro/appstore/binary-"
base_url_appendix="/Packages.gz"
target_package="com.tencent.wechat"
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 "apt" -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;
        }
    }
    ')
    hash+=("$(nix --extra-experimental-features nix-command hash convert --hash-algo sha256 --to sri $sha256sum)")
    url+=("https://pro-store-packages.uniontech.com/appstore/pool/appstore/c/com.tencent.wechat/com.tencent.wechat_"$version"_"$i".deb")
done

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

rm -r Packages.gz
