#!/bin/bash
# file: frontend_condortoken
# purpose: generates a condor IDTOKEN for authorizing back to the frontend
#         from a glideinwms factory entry.  Echos token to stdout
# arguments:
#      KEY: the name of the factory entry 
# author:  Dennis Box, dbox@fnal.gov
#
KEY=$1
ID=$(whoami)
FRONTEND=$(stat --format '%U' /etc/gwms-frontend/frontend.xml)
if [ ! "${ID}" = "${FRONTEND}" ]; then
	echo "this script may only be run by user ${FRONTEND}"
	exit 1
fi


if [ "$KEY" = "" ]; then
	echo "usage $0 factory_entry"
	echo creates frontend token for factory_entry and echos it to stdout
	exit 0
fi

# create a key for creating the token if needed
if [ ! -e "/etc/condor/passwords.d/${KEY}" ]; then
    openssl rand -base64 64 | sudo /usr/sbin/condor_store_cred -u "frontend@${HOSTNAME}" -f "/etc/condor/passwords.d/${KEY}" add > /dev/null 2>&1
fi

AUTH='-authz READ -authz WRITE -authz ADVERTISE_STARTD -authz ADVERTISE_SCHEDD -authz ADVERTISE_MASTER'

# create the token, echo it to stdout
sudo /usr/bin/condor_token_create  -lifetime 86400 -key ${KEY} ${AUTH} -identity "${ID}@${HOSTNAME}"
