#!/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 CustomResourceDefinition"
    ./lib/check-permissions.sh "patch CustomResourceDefinition"
}

upgradeCRDs() {
    command="kubectl apply -f crd"
    ./lib/msg.sh "Applying custom resource definitions from the 'crd' directory: $command"
    eval "$command"
}

main() {
    parseParams "$@"

    ./lib/msg.sh ""
    ./lib/msg.sh "-------- CRD-upgrade ---------"

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

    ./lib/msg.sh "This step upgrades the custom resource definitions."
    ./lib/msg.sh "Note that this step can not be rolled back."

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

    runChecks
    upgradeCRDs
    ./lib/msg.sh "CRD-upgrade completed."
}

main "$@"
