#!/usr/bin/env bash

. lib.bash || exit

usage() {
	echo "Usage: ${0##*/} <options>"
	echo ""
	echo_opt "-c PATH" "certificate file (PEM)"
	echo_opt "-k PATH" "private-key file (PEM)"
	echo_opt "-I IDENTITY" "raw identity specifier (PKCS11:, PKCS12:)"
	echo_opt "-P NAME" "client principal"
}

opt_identity=
opt_principal=
opt_cert=
opt_key=
opt_refresh=0

while getopts ":c:k:I:P:R" OPT; do
	case $OPT in
	c) opt_cert=$OPTARG;;
	k) opt_key=$OPTARG;;
	I) opt_identity=$OPTARG;;
	P) opt_principal=$OPTARG;;
	R) opt_refresh=1;;
	*) lib:die_getopts;;
	esac
done; shift $((OPTIND-1))

if [[ ! $opt_principal ]]; then
	opt_principal="$(pklist -P)"
fi

if [[ ! $opt_principal ]]; then
	opt_principal="$(whoami)@$(pklist -R)"
	if [[ $opt_principal == *@ ]]; then
		die "could not determine default realm"
	fi
fi

if [[ $opt_cert ]]; then
	opt_identity="FILE:$(realpath -s "$opt_cert")"
	if [[ $opt_key ]]; then
		opt_identity+=",$(realpath -s "$opt_key")"
	fi
fi

if [[ ! $opt_identity ]] && (( opt_refresh )); then
	opt_identity=$(pklist -C |
			awk '$1 == "config" && $3 == "pa_config_data" {print $5}' |
			unescape |
			jq -r '.X509_user_identity')
fi

if [[ ! $opt_identity ]]; then
	die "identity not specified"
fi

if [[ -f $opt_identity ]]; then
	if [[ $opt_identity == *.@(p12|pkcs12|pfx) ]]; then
		opt_identity="PKCS12:$(realpath -s "$opt_identity")"
	else
		opt_identity="FILE:$(realpath -s "$opt_identity")"
	fi
fi

kinit -X "X509_user_identity=$opt_identity" "$@" "$opt_principal"
