#!/bin/bash


fail () {
    set +exu
    ret=$1
    shift &>/dev/null || :
    echo "$*" >&2
    exit "$ret"
}


usage () {
    echo >&2 "Usage: $(basename "$0") <token file> <command>..."
    echo >&2
    echo >&2 "Run the given command with the environment variables set up such as to use the token provided on the command line."
    echo >&2
}

if [[ $1 == -h || $1 == --help ]]; then
    usage
    exit 0
fi


token=$1
shift &>/dev/null || :

if [[ ! $token ]]; then
    usage
    fail 2 Token not provided
fi

if [[ ! $* ]]; then
    usage
    fail 2 Command not provided
fi

if [[ ! -f $token || ! -r $token ]]; then
    ls -ld "$token" >&2
    fail 3 Token not a file or not readable
fi

set -u


tokendir=$(mktemp -d "${TMPDIR:-/var/tmp}/with-token-XXXXXX")
[[ $tokendir && -d $tokendir ]]  ||  fail 4 Could not create temp directory
trap "rm -rf \"${tokendir:?}\"" EXIT
basetoken=$(basename "$token")
[[ $basetoken ]]  ||  fail 5 "Could not get basename of token $token"

install -o "$(id -u)" -g "$(id -g)" -m 0600 "$token" "${tokendir}/${basetoken}"  ||  fail 6 Could not copy token

export _CONDOR_SEC_TOKEN_DIRECTORY="$tokendir"
export _CONDOR_SEC_CLIENT_AUTHENTICATION_METHODS="IDTOKENS"
export _CONDOR_SEC_CLIENT_AUTHENTICATION="REQUIRED"

"$@"

