#!/usr/bin/bash

# Your GitHub username and access token
username="<Replace with your GitHub username>"
access_token="<Replace with your access token with workflow scope>"

artifact="$(curl https://api.github.com/repos/bjorn3/rustc_codegen_cranelift/actions/artifacts | jq -c ".artifacts|map(select(.name==\"cg_clif-Linux\"))[0]")"
id="$(echo "$artifact" | jq .id)"
expired="$(echo "$artifact" | jq .expired)"

if [ "$(cat /opt/cargo-clif/artifact-id 2>&-)" = "$id" ]; then
    echo cargo-clif is up to date
    exit
elif [ "$expired" = "true" ]; then
    echo New version is already expired >&2
    false
    exit
else
    sudo mkdir -p /opt/cargo-clif
    sudo bash -c "echo $id > /opt/cargo-clif/artifact-id"
fi

sudo rm -rf /opt/cargo-clif/lib/librustc_std* /opt/cargo-clif/lib/rustlib/x86_64-unknown-linux-gnu/lib/*
curl -Lu$username:$access_token "$(echo "$artifact" | jq -r .archive_download_url)" | funzip | sudo tar xJC /opt/cargo-clif --strip-components 1
if [ ! -e /usr/local/bin/cargo-clif ]; then
    sudo ln -s /opt/cargo-clif/cargo /usr/local/bin/cargo-clif
fi
