#!/bin/bash

clear

ESC=`printf "\033"`;

input_key() {
    read -s -n3 INPUT;
    echo $INPUT;
}

check_selected() {
    if [ $1 = $2 ];
    then echo " => "
    else echo "    "
    fi
}

select_menu() {
    SELECTED=1;
    INPUT="";
    MIN_MENU=1;
    MAX_MENU=$#;

    while true;
    do
        for (( i=1; i<=$#; i++ ))
        do
            printf "$ESC[2K$(check_selected $i $SELECTED) $i. ${!i}\n";
        done
        printf "\n$ESC[2KCMOA\nVersion: 3.5.5\n";
        INPUT=$(input_key);
        if [[ $INPUT = "" ]];
        then break;
        fi

        if [[ $INPUT = $ESC[A ]];
        then SELECTED=$(expr $SELECTED - 1);
        elif [[ $INPUT = $ESC[B ]];
        then SELECTED=$(expr $SELECTED + 1);
        fi

        if [[ $SELECTED -lt $MIN_MENU ]];
        then SELECTED=${MIN_MENU};
        elif [[ $SELECTED -gt $MAX_MENU ]];
        then SELECTED=${MAX_MENU};
        fi

        printf "$ESC[$(expr $# + 3)A";
    done
    return `expr ${SELECTED} - 1`;
}

select_test() {
        arr_params=("CMOA INSTALL" "CMOA PG Patch" "Kubernetes Install (Online Only)");
    echo -e "\n";
    echo ' ______     __    __     ______     ______        __     __   __     ______     ______   ______     __         __         ______     ______   ';
    echo '/\  ___\   /\ "-./  \   /\  __ \   /\  __ \      /\ \   /\ "-.\ \   /\  ___\   /\__  _\ /\  __ \   /\ \       /\ \       /\  ___\   /\  == \  ';
    echo '\ \ \____  \ \ \-./\ \  \ \ \/\ \  \ \  __ \     \ \ \  \ \ \-.  \  \ \___  \  \/_/\ \/ \ \  __ \  \ \ \____  \ \ \____  \ \  __\   \ \  __<  ';
    echo ' \ \_____\  \ \_\ \ \_\  \ \_____\  \ \_\ \_\     \ \_\  \ \_\\"\_\  \/\_____\    \ \_\  \ \_\ \_\  \ \_____\  \ \_____\  \ \_____\  \ \_\ \_\';
    echo '  \/_____/   \/_/  \/_/   \/_____/   \/_/\/_/      \/_/   \/_/ \/_/   \/_____/     \/_/   \/_/\/_/   \/_____/   \/_____/   \/_____/   \/_/ /_/';
    echo -e "\n";
    select_menu "${arr_params[@]}";
    local SELECTED=$?;
    SELECTED_MODE=${arr_params[${SELECTED}]};
}

main() {
    select_test;
    if [ $SELECTED -eq 1 ]
        then
        ansible-playbook -i inventory cmoa_install.yaml
    elif [ $SELECTED -eq 2 ]
        then
        ansible-playbook -i inventory cmoa_pgpatch.yaml
    elif [ $SELECTED -eq 3 ]
        then
        ansible-playbook -i inventory cmoa_infra.yaml
    fi
}
main
