#!/usr/bin/env bash
set -euo pipefail

download-artifact() {
  curl -s -L -O ${ARTIFACT_URL}
  echo "Downloaded artifact '${ARTIFACT_FILENAME}'"
}

download-provenance() {
  curl -s -L -O ${PROVENANCE_URL}
  echo "Downloaded provenance '${PROVENANCE_FILENAME}'"
}

verify() {
  slsa-verifier verify-artifact --provenance-path ${PROVENANCE_FILENAME} ${ARTIFACT_FILENAME} --source-uri "github.com/${REPO}" --source-tag "v${VERSION}"
}

usage() {
  local USAGE
  USAGE="
Usage: $(basename "${0}") [OPTIONS]

This scripts downloads the specified release from a GitHub repository and verifies it with the attached SLSA provenance.

Options:
  -a ARTIFACT    the artifact to download, e.g. macos-notarization-service
  -e EXTENSION   the extension to use, default: .zip
  -r REPO        the GitHub repo to use for download, format: owner/repo-name, e.g. eclipse-cbi/macos-notarization-service
  -v VERSION     the release version to download, e.g. 1.2.0
  -h             show this help

"
  echo "$USAGE"
  exit 1
}


EXTENSION=".zip"

while getopts ":a:e:r:v:" o; do
    case "${o}" in
        a)
            ARTIFACT=${OPTARG}
            ;;
        e)
            EXTENSION=${OPTARG}
            ;;
        r)
            REPO=${OPTARG}
            ;;
        v)
            VERSION=${OPTARG}
            ;;
        *)
            usage
            ;;
    esac
done

shift $((OPTIND-1))

if [ -z "${REPO-}" ] || [ -z "${VERSION-}" ] || [ -z "${ARTIFACT-}" ]; then
    usage
fi

echo "REPO = ${REPO}"
echo "VERSION = ${VERSION}"
echo "ARTIFACT = ${ARTIFACT}"

ARTIFACT_FILENAME="${ARTIFACT}-${VERSION}${EXTENSION}"
ARTIFACT_URL="https://github.com/${REPO}/releases/download/v${VERSION}/${ARTIFACT_FILENAME}"

PROVENANCE_FILENAME="${ARTIFACT_FILENAME}.intoto.jsonl"
PROVENANCE_URL="https://github.com/${REPO}/releases/download/v${VERSION}/${PROVENANCE_FILENAME}"

download-artifact
download-provenance

verify

