#!/bin/sh
die()
{
	printf >&2 "$@"
	exit 1
}
while [[ $# -gt 0 ]]
do
	key="$1"
	case $key in
	-t|--apply_token)
		TOKEN=$2
		shift
		shift
		;;
	-f|--output_file)
		OPFILE=$2
		shift
		shift
		;;
	*)
		die "Invalid arguments. Exiting.\nUsage: $0 [-t <token> -f <output_yaml_file>]\n"
		exit 1
		;;
	esac
done
if [ ! -z "$TOKEN" -a -z "$OPFILE" ]; then
	die "Provide output file path to apply using -f <output_yaml_file> to apply the role.\n"
fi
TOKEN_ARG=""
if [ ! -z $TOKEN ]; then
	TOKEN_ARG="--token $TOKEN"
fi
#if output file not provided, default to output to stdout.
if [ -z $OPFILE ]; then
	OPFILE="/dev/stdout"
else
	echo "Will create output yaml file at $OPFILE"
fi
#Clear contents if non-empty.
echo "" > $OPFILE 
echo -e "apiVersion: rbac.authorization.k8s.io/v1\n\
kind: ClusterRole\n\
metadata:\n\
  name: cv-role\n\
rules:\n" >> $OPFILE
echo -e "- apiGroups: [\"*\"]\n\
  resources: [\"pods/exec\"]\n\
  verbs: [\"*\"]\n" >> $OPFILE
RESOURCES=`kubectl api-resources | awk '{print $1}' | tail -n +2 | cut -d '.' -f 2- | sort | uniq |  sed 's/.*/  - "&"/g'`
echo -e "- apiGroups: [\"*\"]\n\
  resources: \n\
${RESOURCES}
  verbs: [\"*\"]\n" >> $OPFILE
#if this is set, we need to apply the created role.
if [ ! -z "$TOKEN_ARG" ]; then
	echo "Applying $OPFILE"
	kubectl apply -f $OPFILE $TOKEN_ARG
fi