#!/bin/bash

#Declare the number of mandatory args: operator_name 
NUM_MANDATORY_ARGS=1

function example {
    echo -e "example: acquiring a provisioning cert for a provisioning machine without tpm:\n  $SCRIPT_NAME --operator OPERATOR_NAME --token TOKEN --with-op-tpm false"
}

function usage {
    echo -e "usage: $SCRIPT_NAME MANDATORY [OPTION]\n"
}

function help {
  usage
    echo -e "MANDATORY:"
    echo -e "  -o, --operator           OP_NAME         Name of the operator for whom the cert is being generated"
    echo -e "OPTION:"
    echo -e "  -t, --token              TOKEN           Vault access token used for cert generation. If not provided, a 2FA login will be required [default: empty string]"
    echo -e "  -v, --vault              VAULT_ADDR      Address of the signer [default: https://vault-rsi.zooxlabs.com]"
    echo -e "  -w, --with-op-tpm        OP_TPM          Specifies if the cert and sealed key should be stored on the machine's tpm device (true/false) [default: false]"
    echo -e "  -h, --help                               Prints this help\n"
  example
}

# Ensures that the number of passed args are at least equal
# to the declared number of mandatory args.
# It also handles the special case of the -h or --help arg.
function mandatory_args_precheck {
    if [ "$2" ] && [ "$1" -lt "$NUM_MANDATORY_ARGS" ]; then
        if [ "$2" == "--help" ] || [ "$2" == "-h" ]; then
            help
            exit
        else
            usage
            example
            exit 1
        fi
    fi
}

# Ensures that all the mandatory args are not empty
function mandatory_args_check {
    if [ $# -lt "$NUM_MANDATORY_ARGS" ]; then
    usage
    example
    exit 1
    fi
}

mandatory_args_precheck $# "$1"

# Args while-loop
while (( "$#" ));
do
    case $1 in
        -v  | --vault )
            shift
            VAULT_ADDR=$1
            ;;
        -o | --operator )
            shift
            OP_NAME=$1
            ;;
        -t | --token )
            shift
            VAULT_TOKEN=$1
            ;;
        -w | --with-op-tpm )
            shift
            OP_TPM=$1
            ;;
        -h   | --help )
            help
            exit
            ;;
        *)
            echo "$SCRIPT_NAME: illegal option $1"
            usage
            example
            exit 1 # error
            ;;
    esac
    shift
done

# Add list of mandatory arguments here.
mandatory_args_check "$OP_NAME"
