#!/bin/sh
if [ ! "$KROOT_PRINCIPAL" ]; then
    export KROOT_PRINCIPAL="${USER}/root"
fi
export KRB5CCNAME=/tmp/krb5cc_${UID}.root # Currently assumes this is safe.
export KRBTKFILE=/dev/null
export debian_chroot=${debian_chroot+$debian_chroot|}${KROOT_PRINCIPAL}

get_tickets() {
    klist -s || "$0" init || exit 1;
}

case "$1" in
    init)
        shift;
        exec kinit -F -5 -l15m "${KROOT_PRINCIPAL}"@ATHENA.MIT.EDU "$@"
        ;;
    destroy)
        exec kdestroy -5
        ;;
    shell)
        get_tickets
        pagsh -c "aklog athena 2>/dev/null; aklog sipb 2>/dev/null; $SHELL"
        "$0" destroy
        ;;
    ssh)
        get_tickets
        shift;
        exec ssh -k -l root "$@"
        ;;
    rlogin)
        get_tickets
        shift;
        exec rlogin -x -l root "$@"
        ;;
    help|-help|--help|-h|-?)
        echo "Usage: $0 help: This help message" >&2
        echo "       $0 init: Get root tickets" >&2
        echo "       $0 destroy: Destroy root tickets" >&2
        echo "       $0 shell: Start a new shell in a new PAG with root tickets/tokens" >&2
        echo "       $0 ssh ARGS: ssh -k -l root ARGS" >&2
        echo "       $0 [cmd]: Run command with root tickets" >&2
        echo "       $0: (same as shell)" >&2
        ;;
    *)
        if [ "$#" = 0 ]; then
            "$0" shell
        else
            get_tickets
            exec "$@"
        fi
        ;;
esac
