# Put in your SUNet ID.
# If your local username IS your SUNet ID, you can just enter "$USER" instead.
SUNETID=$USER

# Put in the hostname (JUST the hostname) of your group's bastion host
BASTION=luckdragon
#BASTION=dr

# If you want to change the name of the principal-switching commands,
# or you want to change the name of the SSH-related commands,
# look at the bottom of the script.

#
# CODE BEGINS HERE!
#

# Support multiple Kerberos principals
# Takes one parameter, which is the type of principal to switch to
# (either empty string, 'root', 'admin', or 'sunet').
pag_switch() {
	# Check the PAG type we're switching to
	type=$1
	if [ "$type" = '' ]; then
		TARGET_PRINCIPAL="${SUNETID}@stanford.edu"
		FORWARDABLE=1
		type='regular'
	elif [ "$type" = 'root' ]; then
		TARGET_PRINCIPAL="${SUNETID}/root@stanford.edu"
		FORWARDABLE=0
	elif [ "$type" = 'admin' ]; then
		TARGET_PRINCIPAL="${SUNETID}/admin@stanford.edu"
		FORWARDABLE=0
	elif [ "$type" = 'sunet' ]; then
		TARGET_PRINCIPAL="${SUNETID}/sunet@stanford.edu"
		FORWARDABLE=0
	else
		echo "Invalid pag type $type"
		return
	fi

	# Save the original $PS1
	if [ -z ${PS1ORIG+x} ]; then
		PS1ORIG=$PS1
		export PS1ORIG
	fi

	# Some credentials can't be forwarded
	if [ $FORWARDABLE = 1 ]; then
		KINIT_OPTIONS=''
	else
		KINIT_OPTIONS='--no-forwardable'
	fi
	KINIT_COMMAND="kinit $KINIT_OPTIONS $TARGET_PRINCIPAL"

	# Set prompts
	PS1="(${type}-failed) $PS1ORIG"
	NEWPS1="(${type}) $PS1ORIG"

	# Try switching
	echo "Switching to $TARGET_PRINCIPAL"
	need_kinit=0
	kswitch -p $TARGET_PRINCIPAL 2> /dev/null
	if [ $? -eq 1 ]; then
		need_kinit=1
	else
		klist -t
		if [ $? -eq 1 ]; then
			need_kinit=1
		fi
	fi

	# If we need to kinit, do it now
	if [ $need_kinit -eq 1 ]; then
		$KINIT_COMMAND
		if [ $? -eq 0 ]; then
			PS1=$NEWPS1
		fi
	else
		PS1=$NEWPS1
	fi

	# Block kdestroy and kswitch
	alias kdestroy='echo "Please do not use kdestroy when PAG-switched."'
	alias kswitch='echo "Please do not use kswitch when PAG-switched."'
}

# SSH functions for connecting to Stanford systems.
ssh_stanford() {
	ssh -l $SUNETID $1.stanford.edu
}
ssh_stanford_root() {
	ssh -l root $1.stanford.edu
}

#
# CODE ENDS
# 

# Principal-switching aliases
# You can change the alias names to whatever you like, just so long as
# everything to the right of the = is unchanged.
alias pag='pag_switch'
alias rootpag='pag_switch root'
alias adminpag='pag_switch admin'
alias sunetpag='pag_switch sunet'

# SSH aliases
alias sshs=ssh_stanford
alias sshr=ssh_stanford_root
alias bastion='pag; exec ssh -p 44 -l $SUNETID $BASTION.stanford.edu bin/luckdragon.sh'

