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

set -euo pipefail

cd $(readlink -e $(dirname "${BASH_SOURCE[0]}"))

# darwin

darwin_url=$(curl -s https://im.qq.com/macqq/index.shtml | grep -oP 'var rainbowConfigUrl = "\K.*(?=";)')
darwin_payload=$(curl "$darwin_url" | grep -oP "var params= \K\{.*\}(?=;)")
darwin_version=$(jq -r .version <<< "$darwin_payload" | awk -F\  '{print $1}')-$(jq -r .updateDate <<< "$darwin_payload")

darwin_url=$(jq -r .downloadUrl <<< "$darwin_payload")

darwin_hash=$(nix-prefetch-url $darwin_url)

# use friendlier hashes
darwin_hash=$(nix hash convert --to sri --hash-algo sha256 "$darwin_hash")

# linux

linux_url=$(curl -s https://im.qq.com/linuxqq/index.shtml | grep -oP 'var rainbowConfigUrl = "\K.*(?=";)')
linux_payload=$(curl "$linux_url" | grep -oP "var params= \K\{.*\}(?=;)")
linux_version=$(jq -r .version <<< "$linux_payload")-$(jq -r .updateDate <<< "$linux_payload")

linux_aarch64_url=$(jq -r .armDownloadUrl.deb <<< "$linux_payload")
linux_x86_64_url=$(jq -r .x64DownloadUrl.deb <<< "$linux_payload")

linux_aarch64_hash=$(nix-prefetch-url $linux_aarch64_url)
linux_x86_64_hash=$(nix-prefetch-url $linux_x86_64_url)

# use friendlier hashes
linux_aarch64_hash=$(nix hash convert --to sri --hash-algo sha256 "$linux_aarch64_hash")
linux_x86_64_hash=$(nix hash convert --to sri --hash-algo sha256 "$linux_x86_64_hash")

cat >sources.nix <<EOF
# Generated by ./update.sh - do not update manually!
# Last updated: $(date +%F)
{ fetchurl }:
let
  any-darwin = {
    version = "$darwin_version";
    src = fetchurl {
      url = "$darwin_url";
      hash = "$darwin_hash";
    };
  };
in
{
  aarch64-darwin = any-darwin;
  x86_64-darwin = any-darwin;
  aarch64-linux = {
    version = "$linux_version";
    src = fetchurl {
      url = "$linux_aarch64_url";
      hash = "$linux_aarch64_hash";
    };
  };
  x86_64-linux = {
    version = "$linux_version";
    src = fetchurl {
      url = "$linux_x86_64_url";
      hash = "$linux_x86_64_hash";
    };
  };
}
EOF
