#!/usr/bin/env bash

set -Eeuo pipefail

isRollback=false

parseParams() {
    while :; do
        case "${1-}" in
        --rollback) isRollback=true ;;
        -?*) ./lib/die.sh "Unknown option: $1" ;;
        *) break ;;
        esac
        shift
    done
}

runChecks() {
    ./lib/msg.sh "Checking permissions..."
    ./lib/check-permissions.sh "create ClusterRole"
    ./lib/check-permissions.sh "patch ClusterRole"
    ./lib/check-permissions.sh "create ClusterRoleBinding"
    ./lib/check-permissions.sh "patch ClusterRoleBinding"
}

upgradePermissions() {
    command="kubectl apply -f rbac"
    ./lib/msg.sh "Applying permissions from the 'rbac' directory: $command"
    eval "$command"
}

main() {
    parseParams "$@"

    ./lib/msg.sh ""
    ./lib/msg.sh "-------- Update RBAC permissions ---------"

    if [[ $isRollback == true ]]; then
        ./lib/msg.sh "Permission update cannot be rolled back."
        return
    fi

    ./lib/msg.sh "This step updates the RBAC permissions used by nevisAdmin4 and the nevisOperator."
    ./lib/msg.sh "Note that this step can not be rolled back."

    read -p "Update permissions? [y/n]" -n 1 -r
    printf '\n'
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        return
    fi

    runChecks
    upgradePermissions
    ./lib/msg.sh "RBAC permission update completed."
}

main "$@"