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

set -euo pipefail

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

aarch64_darwin_data=$(curl -s 'https://slack.com/api/desktop.latestRelease?arch=arm64&variant=dmg')
x86_64_darwin_data=$(curl -s 'https://slack.com/api/desktop.latestRelease?arch=x64&variant=dmg')
x86_64_linux_data=$(curl -s 'https://slack.com/api/desktop.latestRelease?arch=x64&variant=deb')

aarch64_darwin_version=$(jq -r .version <<< "$aarch64_darwin_data")
x86_64_darwin_version=$(jq -r .version <<< "$x86_64_darwin_data")
x86_64_linux_version=$(jq -r .version <<< "$x86_64_linux_data")

aarch64_darwin_url=$(jq -r .download_url <<< "$aarch64_darwin_data")
x86_64_darwin_url=$(jq -r .download_url <<< "$x86_64_darwin_data")
x86_64_linux_url=$(jq -r .download_url <<< "$x86_64_linux_data")

aarch64_darwin_hash=$(nix-prefetch-url "$aarch64_darwin_url")
x86_64_darwin_hash=$(nix-prefetch-url "$x86_64_darwin_url")
x86_64_linux_hash=$(nix-prefetch-url "$x86_64_linux_url")

# use friendlier hashes

aarch64_darwin_hash=$(nix --extra-experimental-features nix-command hash convert --to sri --hash-algo sha256 "$aarch64_darwin_hash")
x86_64_darwin_hash=$(nix --extra-experimental-features nix-command hash convert --to sri --hash-algo sha256 "$x86_64_darwin_hash")
x86_64_linux_hash=$(nix --extra-experimental-features nix-command hash convert --to sri --hash-algo sha256 "$x86_64_linux_hash")

cat >sources.nix <<EOF
# Generated by ./update.sh - do not update manually!
# Last updated: $(date +%F)
{ fetchurl }:
{
  aarch64-darwin = {
    version = "$aarch64_darwin_version";
    src = fetchurl {
      url = "$aarch64_darwin_url";
      hash = "$aarch64_darwin_hash";
    };
  };
  x86_64-darwin = {
    version = "$x86_64_darwin_version";
    src = fetchurl {
      url = "$x86_64_darwin_url";
      hash = "$x86_64_darwin_hash";
    };
  };
  x86_64-linux = {
    version = "$x86_64_linux_version";
    src = fetchurl {
      url = "$x86_64_linux_url";
      hash = "$x86_64_linux_hash";
    };
  };
}
EOF
