#!/bin/bash
#
##########################################################################
#
###!!! GET THESE VALUES FROM CALLING SCRIPT automate-010-install-HANA
version="4.0.2022.06.29.1"
#
##########################################################################
#
TAG="fh_reset_ScaleUp"

#
# QUIET MODE!!
#
echo "$(date) == fh_reset_ScaleUp STARTING" >&3
echo "$(date) == prim=$prim" >&3

#
# unmanage
function unmanage()
{
    local res="$1"
    local rc=0
    logger -s -i -t $TAG "unmanage $res"
    crm resource unmanage $res; rc=$?
    logger -s -i -t $TAG "rc=$rc"
    echo "$(date) rc=$rc" >&3
    return $rc
}


#
# manage
function manage()
{
    local res="$1"
    local rc=0
    logger -s -i -t $TAG "manage $res"
    crm resource manage $res; rc=$?
    logger -s -i -t $TAG "rc=$rc"
    echo "$(date) rc=$rc" >&3
    return $rc
}

#
# cleanup
function cleanup()
{
    local res="$1"
    local rc=0
    logger -s -i -t $TAG "cleanup $res"
    crm resource cleanup $res; rc=$?
}

function stop_system()
{
    # stop_system <sid> <ino> <node>
    local rc=0
    local sid="${1,,}" ino="$2" node="$3"
    local COMMAND
    logger -s -i -t $TAG "stop_system"
    COMMAND="hostname; sapcontrol -nr $ino -function StopSystem; sapcontrol -nr $ino -function WaitforStopped 300 10; hostname"
    ssh root@"$node" "su - ${sid}adm -c '$COMMAND'"; rc=$?
    logger -s -i -t $TAG "rc=$rc"
    return $rc
}

function start_system()
{
    # start_system <sid> <ino> <node>
    local rc=0
    local sid="${1,,}" ino="$2" node="$3"
    local COMMAND
    logger -s -i -t $TAG "start_system"
    COMMAND="hostname; sapcontrol -nr $ino -function StartSystem; sapcontrol -nr $ino -function WaitforStarted 300 10; hostname"
    ssh root@"$node" "su - ${sid}adm -c '$COMMAND'"; rc=$?
    logger -s -i -t $TAG "rc=$rc"
    return $rc
}

#
# Stop secondary system
# TODO: remove after checking new functions
#
function stop_secondary()
{
    local rc=0
    logger -s -i -t $TAG "stop_secondary"
    echo "$(date) stop_secondary" >&3
    COMMAND="hostname; sapcontrol -nr $ino -function StopSystem; sapcontrol -nr $ino -function WaitforStopped 300 10; hostname"
    ssh root@$secn "su - ${sid}adm -c '$COMMAND'"; rc=$?
    logger -s -i -t $TAG "rc=$rc"
    echo "$(date) rc=$rc" >&3
    return $rc
}

#
# Stop primary system
# TODO: remove after checking new functions
#
function stop_primary()
{
    local rc=0
    logger -s -i -t $TAG "stop_primary"
    echo "$(date) stop_primary" >&3
    COMMAND="hostname; sapcontrol -nr $ino -function StopSystem; sapcontrol -nr $ino -function WaitforStopped 300 10; hostname"
    ssh root@$prim "su - ${sid}adm -c '$COMMAND'"; rc=$?
    logger -s -i -t $TAG "rc=$rc"
    echo "$(date) rc=$rc" >&3
    return $rc
}

###
# Uninstall primary
# TODO: could we change to hdblcm
function uninstall_primary()
{ 
    local rc=0
    local SID="$1" ino="$2" node="$3"
logger -s -i -t $TAG "uninstall_primary"
    echo "$(date) uninstall_primary" >&3
    COMMAND="$HANA_INST_DIR/hdbuninst \
        --batch \
        --sid=$SID \
         "
    ssh root@$prim "$COMMAND"; rc=$?
    logger -s -i -t $TAG "rc=$rc"
    echo "$(date) rc=$rc" >&3
    return $rc
}

###
# Uninstall secondary
# TODO: could we change to hdblcm - maybe keep hdbinst function as backword reference
function uninstall_secondary()
{
    local rc=0
    logger -s -i -t $TAG "uninstall_secondary"
    echo "$(date) uninstall_secondary" >&3
    COMMAND="$HANA_INST_DIR/hdbuninst \
        --batch \
        --sid=$SID \
        "
    ssh root@$secn "$COMMAND"; rc=$?
    logger -s -i -t $TAG "rc=$rc"
    echo "$(date) rc=$rc" >&3
    return $rc
}

###
# Install primary
function install_primary()
{
    local rc=0
    logger -s -i -t $TAG "install_primary"
    echo "$(date) install_primary ($prim)" >&3
    rsync -va $FILES/hana_passwords root@$prim:.
    #
    COMMAND="cat hana_passwords | $HANA_INST_DIR/hdbinst \
              --batch \
              --sid=${SID} --number=${ino} \
              --import_content=off \
              --ignore=check_min_mem  \
              --db_mode=multiple_containers \
              --read_password_from_stdin=xml \
              --install_hostagent \
              --datapath=/hana/data/${SID} \
              --logpath=/hana/log/${SID} \
    "
              #--isc_mode=standard \
              #--remote_execution=saphostagent \
    ssh root@$prim "$COMMAND"; rc=$?
    logger -s -i -t $TAG "rc=$rc"
    echo "$(date) rc=$rc" >&3
    return $rc
}

###
# Install secondary
function install_secondary()
{
    local rc=0
    logger -s -i -t $TAG "install_secondary"
    echo "$(date) install_secondary" >&3
    rsync -va $FILES/hana_passwords root@$secn:.

    # TODO: Take ignore, import_content, db_mode and password from the repository
    COMMAND="cat ~/hana_passwords | $HANA_INST_DIR/hdbinst \
              --batch \
              --sid=${SID} --number=${ino} \
              --import_content=off \
              --ignore=check_min_mem \
              --db_mode=multiple_containers \
              --read_password_from_stdin=xml \
              --install_hostagent \
              --datapath=/hana/data/${SID} \
              --logpath=/hana/log/${SID} \
    "
    echo "CMD: $COMMAND" >&3
              # --remote_execution=saphostagent \
    ssh root@$secn "$COMMAND"; rc=$?
    logger -s -i -t $TAG "rc=$rc"
    echo "$(date) rc=$rc" >&3
    return $rc
}

function install_with_hdblcm()
{
    # install_secondary_hdblcm <sid> <ino> <node> 
    local rc=0
    local SID="$1" ino="$2" node="$3" 
    logger -s -i -t $TAG "install_secondary_hdblcm"
    rsync -va $FILES/hana_passwords root@$node:.

    # TODO: Take ignore, import_content, db_mode and password from the repository
    COMMAND="cat ~/hana_passwords | $HANA_INST_DIR/hdblcm \
              --batch \
              --action=install \
              --sid=${SID} --number=${ino} \
              --install_hostagent \
              --ignore=check_min_mem,check_signature_file \
              --read_password_from_stdin=xml \
    "
              # --remote_execution=saphostagent \
              #--components=client \
              # not in hdblcm: --db_mode=multiple_containers \
              #--import_content=off \
    ssh root@$node "$COMMAND"; rc=$?
    logger -s -i -t $TAG "rc=$rc"
    return $rc
}

function uninstall_with_hdblcm()
{
    # uninstall_with_hdblcm <sid> <ino> <node>
    local rc=0
    local SID="$1" ino="$2" node="$3" 
    logger -s -i -t $TAG "install_secondary_hdblcm"
    rsync -va $FILES/hana_passwords root@$secn:.

    # TODO: Take ignore, import_content, db_mode and password from the repository
    COMMAND="/hana/shared/HA1/hdblcm/hdblcm \
              --batch \
              --uninstall \
              --sid=${SID} \
    "
              # --remote_execution=saphostagent \
              # not in hdblcm: --db_mode=multiple_containers \
              #--import_content=off \
    ssh root@$node "$COMMAND"; rc=$?
    logger -s -i -t $TAG "rc=$rc"
    return $rc
}

####
# BACKUP PRIMARY SYSTEM
function backup_primary()
{
    local rc=0
    local SID="$1" ino="$2" node="$3" file="$4"
    logger -s -i -t $TAG "backup_primary"
    echo "$(date) backup_primary" >&3
    # TODO: Take passwd from the repository; take dbmode from the repository
    COMMAND="/usr/sap/$SID/HDB${ino}/exe/hdbsql \
          -d SYSTEMDB -u system -p SuSE1234 -i ${ino} \
          \"BACKUP DATA FOR FULL SYSTEM USING FILE ('$file')\"
    "
    ssh root@"$node" "$COMMAND"; rc="$?"
    logger -s -i -t $TAG "rc=$rc"
    echo "$(date) rc=$rc" >&3
    return "$rc"
}

####
# ENABLE AT PRIMARY
function enable_primary()
{ 
    local rc=0
    local SID="$1" ino="$2" node="$3" primSite="$4"
    logger -s -i -t $TAG "enable_primary"
    echo "$(date) enable_primary" >&3
    COMMAND="hostname; hdbnsutil -sr_enable --name=${primSite}"
    ssh root@"$node" "su - ${sid}adm -c '$COMMAND'"; rc="$?"
    logger -s -i -t $TAG "rc=$rc"
    echo "$(date) rc=$rc" >&3
    return "$rc"
}

####
# REGISTER SECONDARY
function register_system()
{
    local rc=0
    local SID="$1" ino="$2" node="$3" site="$4" prim="$5"
    logger -s -i -t $TAG "register_system"
    echo "$(date) register_system" >&3
    # FOR HANA 2.0
    #
    ssh -A ${prim} rsync -va /hana/shared/${SID}/global/security/rsecssfs/ $secn:/hana/shared/${SID}/global/security/rsecssfs
    # FOR OLD PARAM SET
    # COMMAND="hostname; hdbnsutil -sr_register --remoteHost=${prim} --remoteInstance=${ino} --mode=async --name=${secnSite} --force_full_replica"
    COMMAND="hostname; hdbnsutil -sr_register \
           --remoteHost=${prim} --remoteInstance=${ino} \
           --replicationMode=sync \
           --operationMode=logreplay \
           --name=${site} \
           --force_full_replica
    "
    ssh root@"$node" "su - ${sid}adm -c '$COMMAND'"; rc="$?"
    logger -s -i -t $TAG "rc=$rc"
    echo "$(date) rc=$rc" >&3
    return $rc
}

function unregister_secondary()
{
    local rc=0
    logger -s -i -t $TAG "unregister_secondary"
    echo "$(date) register_secondary" >&3
    # FOR HANA 2.0
    #
    #ssh -A ${prim} rsync -va /hana/shared/${SID}/global/security/rsecssfs/ $secn:/hana/shared/${SID}/global/security/rsecssfs
    # FOR OLD PARAM SET
    # COMMAND="hostname; hdbnsutil -sr_register --remoteHost=${prim} --remoteInstance=${ino} --mode=async --name=${secnSite} --force_full_replica"
    COMMAND="hostname; hdbnsutil -sr_unregister \
    "
    ssh root@$secn "su - ${sid}adm -c '$COMMAND'"; rc=$?
    logger -s -i -t $TAG "rc=$rc"
    echo "$(date) rc=$rc" >&3
    return $rc
}

function cleanup_primary()
{
    local rc=0
    logger -s -i -t $TAG "cleanup_primary"
    echo "$(date) cleanup_primary" >&3
    COMMAND="hostname; hdbnsutil -sr_cleanup --force; hostname"
    ssh root@$secn "su - ${sid}adm -c '$COMMAND'"; rc=$?
    logger -s -i -t $TAG "rc=$rc"
    echo "$(date) rc=$rc" >&3
    return $rc
}

####
# START PRIMARY
function start_primary()
{ 
    local rc=0
    logger -s -i -t $TAG "start_primary"
    echo "$(date) start_primary" >&3
    COMMAND="hostname; hostname; sapcontrol -nr $ino -function StartSystem; sapcontrol -nr $ino -function WaitforStarted 300 10; hostname"
    ssh root@$prim "su - ${sid}adm -c '$COMMAND'"; rc=$?
    logger -s -i -t $TAG "rc=$rc"
    echo "$(date) rc=$rc" >&3
    return $rc
}

####
# START SECONDARY
function start_secondary()
{ 
    local rc=0
    logger -s -i -t $TAG "start_secondary"
    echo "$(date) start_secondary" >&3
    COMMAND="hostname; hostname; sapcontrol -nr $ino -function StartSystem; sapcontrol -nr $ino -function WaitforStarted 300 10; hostname"
    ssh root@$secn "su - ${sid}adm -c '$COMMAND'"; rc=$?
    logger -s -i -t $TAG "rc=$rc"
    echo "$(date) rc=$rc" >&3
    return $rc
}

function manually_check_nameserver_ini()
{
    local rc=1
    logger -s -i -t $TAG "manually_check_nameserver_ini"
    ok=0
    COMMAND="hostname; cat /hana/shared/$SID/global/hdb/custom/config/nameserver.ini"
    ssh root@$secn "su - ${sid}adm -c '$COMMAND'"
    echo "is this nameserver.ini correct?"
    read yn
    case "$yn" in
      "y" | "yes" | "j" | "ja" ) ok=1;;
    esac
 
    if [ $ok -eq 0 ]; then
       echo "EXIT"
       exit 1
    fi
}

check_n_press()
{
 if true; then
   echo "CHECK AND PRESS ENTER" >&3; read
 fi
}

mode=all
steps=""

while [ $# -gt 0 ]; do
    case "$1" in
        --all )
                mode=all;	
                ;;
        --primary )
                mode=primary
                ;;
        --secondary )
                mode=secondary
                ;;
        --third )
                mode=third
                ;;
        --step=* ) # all|uninstall|install|enable|register
                steps="${steps}${steps:+ }${1#--step=}"
                echo "steps=$steps"
                ;;
        --step )
                steps="${steps}${steps:+ }$2"
                echo "steps=$steps"
                shift
                ;;
        * )
                echo "Unknown parameter $1"
                exit 2
                ;;
    esac
    shift
done
if [ -z "$steps" ]; then
    steps=all
else
    steps="${steps//,/ }"
fi

#
# cluster
#
#unmanage msl_SAPHana_${SID}_HDB${ino}
#unmanage cln_SAPHanaTopology_${SID}_HDB${ino}

echo "############ mode=$mode; steps=$steps ###########"

# primary
#
for step in $steps; do
    case "$mode" in
        all | primary )
            case "$step" in
                all )
                    # install_primary || check_n_press
                    install_with_hdblcm "$SID" "$ino" "$prim"  || check_n_press
                    backup_primary "$SID" "$ino" "$prim" "lala" || check_n_press
                    enable_primary "$SID" "$ino" "$prim" "$primSite" || check_n_press
                    ;;
                uninstall )
                    echo "UNISTALL PRIMARY STARTED"
                    # use hdblcm, if installed
                    # uninstall_primary "$SID" "$ino" "$prim" || check_n_press
                    uninstall_with_hdblcm "$SID" "$ino" "$prim" || check_n_press
                    ;;
                install )
                    install_with_hdblcm "$SID" "$ino" "$prim" || check_n_press
                    ;;
                enable )
                    start_system "$SID" "$ino" "$prim" || check_n_press
                    backup_primary "$SID" "$ino" "$prim" "lala" || check_n_press
                    enable_primary "$SID" "$ino" "$prim" "$primSite" || check_n_press
                    ;;
            esac
            ;;
    esac


    case "$mode" in
        all | secondary )
            # secondary
            #
            case "$step" in
                all )
                    install_with_hdblcm "$SID" "$ino" "$secn" "$secnList" || check_n_press
                    stop_system "$SID" "$ino" "$secn" || check_n_press
                    register_system "$SID" "$ino" "$secn" "$secnSite" "$prim" || check_n_press
                    start_system "$SID" "$ino" "$secn" || check_n_press
                    ;;
                uninstall )
                    echo "UNISTALL SECONDARY STARTED"
                    # uninstall_secondary "$SID" "$ino" "$secn"  || check_n_press
                    uninstall_with_hdblcm "$SID" "$ino" "$secn" || check_n_press
                    ;;
                uninstall_hdbinst )
                    echo "UNISTALL SECONDARY STARTED"
                    uninstall_secondary  || check_n_press
                    ;;
                install )
                    install_with_hdblcm "$SID" "$ino" "$secn" || check_n_press
                    ;;
                install_hdblcm )
                    install_with_hdblcm "$SID" "$ino" "$secn" "$secnList" || check_n_press
                    ;;
                register )
                    stop_system "$SID" "$ino" "$secn" || check_n_press
                    register_system "$SID" "$ino" "$secn" "$secnSite" "$prim" || check_n_press
                    start_system "$SID" "$ino" "$secn" || check_n_press
                    ;;
                stop )
                    stop_system "$SID" "$ino" "$secn"
                    ;;
                start )
                    start_system "$SID" "$ino" "$secn"
                    ;;
                unregister )
                    stop_secondary || check_n_press
                    unregister_secondary || check_n_press
                    start_secondary || check_n_press
                    ;;
            esac
            ;;
    esac
    case "$mode" in
        third )
            # third site
            #
            case "$step" in
                stop )
                    stop_system "$SID" "$ino" "$third"
                    ;;
                start )
                    start_system "$SID" "$ino" "$third"
                    ;;
                uninstall )
                    uninstall_with_hdblcm "$SID" "$ino" "$third"  || check_n_press
                    ;;
                install | install_hdblcm )
                    install_with_hdblcm "$SID" "$ino" "$third"  || check_n_press
                    ;;
                register )
                    stop_system "$SID" "$ino" "$third" || check_n_press
                    register_system "$SID" "$ino" "$third" "$thirdSite" "$prim" || check_n_press
                    start_system "$SID" "$ino" "$third" || check_n_press
                    ;;
            esac
            ;;
    esac
done

#
# cluster (2/2)
#
#refresh msl_SAPHana_${SID}_HDB${INO}
#sleep 60
#manage msl_SAPHana_${SID}_HDB${INO}

####
#
# SSH-COPY-ID für alle cluster knoten und user sidadm
