#!/usr/bin/env bash

set -Eeuo pipefail

# Checks if you have permission on the cluster to do something. Takes 2 arguments:
# ${1}: the action you want to see if you have permission for
# ${2}: the namespace (optional)
check_k8s_permissions() {
    if [ "$#" -gt 2 ]; then
        # shellcheck disable=SC2145
        ./lib/die.sh "Check permission call with $# arguments. There should be 1 or 2. An action and an optional namespace."
    fi

    permissionCheckCommand="kubectl auth can-i ${1}"
    if [ "$#" -eq 2 ]; then
        permissionCheckCommand="${permissionCheckCommand} -n ${2}"
    fi
    permissionCheckAnswer=$(eval "$permissionCheckCommand")
    if [[ $permissionCheckAnswer = "yes" ]];
        then ./lib/msg.sh "Permission check for '$permissionCheckCommand' returned '$permissionCheckAnswer'"
        else ./lib/die.sh "Permission check for '$permissionCheckCommand' returned '$permissionCheckAnswer'. Exiting."
    fi
}

check_k8s_permissions "$@"