#!/bin/sh
set -eu

usage() {
    printf '%s\n' 'usage: releasekit MODULE {publish|check|deliver} [ARGS...] | releasekit {version|publication-attempts|reconcile} [ARGS...]' >&2
    exit 2
}

[ "$#" -ge 1 ] || usage
case "$1" in
    core) module_dir=.; profile=releasekit.json ;;
    ckconfig) module_dir=integrations/ckconfig; profile=integrations/ckconfig/releasekit.json ;;
    ckprompt) module_dir=integrations/ckprompt; profile=integrations/ckprompt/releasekit.json ;;
    version|publication-attempts|reconcile) module_dir= ;;
    *) usage ;;
esac

if [ -n "$module_dir" ]; then
    shift
    [ "$#" -ge 1 ] || usage
    operation=$1
    shift
    case "$operation" in
        publish|check|deliver) ;;
        *) usage ;;
    esac
fi

root=$(CDPATH= cd "$(dirname "$0")/.." && pwd)
CDPATH= cd "$root"
GOWORK=off
GOTOOLCHAIN=local
export GOWORK GOTOOLCHAIN
GOOS=$(go env GOHOSTOS)
GOARCH=$(go env GOHOSTARCH)
GOFLAGS="$(go env GOFLAGS) -mod=readonly"
export GOOS GOARCH GOFLAGS

if [ -n "$module_dir" ]; then
    if [ "$operation" = publish ]; then
        set -- "$operation" --repo "$root" --config "$root/$profile" --expected-module "$module_dir" "$@"
    else
        set -- "$operation" --repo "$root" --config "$root/$profile" "$@"
    fi
fi
exec go tool go.maximumdirect.net/releasekit/cmd/releasekit "$@"
