#!/usr/bin/env bash
set -euo pipefail
#
# The accepted cosign invocation pattern for using an environment variable as
# the key is to use <( ... ) substitution, which is not POSIX sh,
# so we use bash.
#
# If <https://github.com/sigstore/cosign/issues/1776> is resolved then the need
# for this wrapper goes away.

progname="$(dirname "$0")"
stderr() { printf >&2 '%s: %s\n' "$progname" "$*"; }
die_n() { e="$1"; shift; stderr "$@"; exit "$e"; }
EX_USAGE=64

[[ -n "${SIGNING_KEY_COSIGN:-}" ]] || die_n $EX_USAGE 'missing env var SIGNING_KEY_COSIGN'

artifact="${1:?need a file to sign}"
signature="${2:?need a file to create}"

: "${COSIGN_PASSWORD:=}"
export COSIGN_PASSWORD

[[ -f "$artifact" ]] || die_n $EX_USAGE "missing input file: ${artifact@Q}"
if [[ -f "$signature" ]]; then
	stderr "deleting pre-existing signature file: ${signature@Q}"
	rm -f -- "$signature"
fi

# We redirect stdin from /dev/null to skip any terminal prompts
# cosign 2.x: requires --yes to say that it's okay to upload to transparency logs
cosign sign-blob \
	--key <( printf '%s\n' "$SIGNING_KEY_COSIGN" ) \
	--output-signature "$signature" \
	--yes \
	"$artifact" \
	</dev/null
