#!/bin/sh
#
#set -x
#
# **********************************************************
# *           liveCache Initialization                      *
# **********************************************************
# *                                                        *
# *    lcinit <lc_name> [ <parameter> ]  [ <userflags> ]   *
# *                                                        *
# **********************************************************

usage () {
  echo
  echo 'USAGE : LCINIT db_name [parameter] [userflags]   '
  echo
  echo '       parameter :                               '
  echo '                     init                        '
  echo '                     restart                     '
  echo '                     register                    '
  echo '                     slow                        '
  echo '                     shutdown                    '
  echo '                     stop                        '
  echo '       userflags :                               '
  echo '                     -uDBM user,pwd              '
  echo '                     -uDBA user,pwd              '
  echo '                     -uSQL user,pwd              '
  echo '                     -ud   pwd                   '
  echo
}

# ==========================================================
# get INSTROOT of this installation
# ==========================================================
get_instroot () {
    inst_root=`$DBMCLI dbm_version INSTROOT`
    rc=$?

    if [ $rc != 0 ]
    then
        # use $DBROOT
        INSTROOT=$DBROOT
    else
        INSTROOT=`echo $inst_root | awk '{split($0,a," "); print a[2]}'`
        # echo $INSTROOT
    fi

    if [ ! -d $INSTROOT ]
    then
        errorexit "ERROR : $INSTROOT does not exist"
    fi
}

# ==========================================================
# check state of the database
# ==========================================================
check_state () {
    dbstate=`$DBMCLI show state`
    echo $dbstate >> $LOGFILE

    if [ `echo $dbstate | grep "WARM" | wc -l ` -gt 0 ] 
    then
        STATE=ONLINE
    elif [ `echo $dbstate | grep "ONLINE" | wc -l ` -gt 0 ] 
    then
        STATE=ONLINE
    elif [ `echo $dbstate | grep "COLD" | wc -l ` -gt 0 ]
    then
        STATE=ADMIN
    elif [ `echo $dbstate | grep "ADMIN" | wc -l ` -gt 0 ]
    then
        STATE=ADMIN
    else
        STATE=OFFLINE
    fi
}

# ==========================================================
# check version of the database
# ==========================================================
check_version () {
    dbvers=`$DBMCLI show version`
    echo
    echo $dbvers | tee -a $LOGFILE
    echo

    # build the versionnumber dbvers.build (7.2.3.005)

    # dbmcli output should be
    # OK SERVERDB: LCE Kernel Version 'Kernel 7.2.4 Build 005-000-213-842'

    vers=`echo $dbvers | awk '{split($0,a,"-"); split(a[1],b," "); print b[7]}'`
    #echo version=$vers
    dbbuild=`echo $dbvers | awk '{split($0,a,"-"); split(a[1],b," "); print b[9]}'`
    #echo build=$dbbuild

    DBVERS=$vers
    DBVERS_BUILD=$vers.$dbbuild
    DBVERS_NR=`echo $DBVERS | sed 's/\./0/g'`

    #echo $DBVERS
    #echo $DBVERS_NR
    echo $DBVERS_BUILD
}

# ==========================================================
# check type (liveCache or OLTP)
# ==========================================================
check_dbtype () {
    dbtype=`$DBMCLI param_directget INSTANCE_TYPE`
    rc=$?

    if [ $rc != 0 ]
    then
        INSTTYPE=DB
    elif [ `echo $dbtype | grep "LVC" | wc -l ` -gt 0 ] 
    then
        INSTTYPE=LVC
    else
        INSTTYPE=DB
    fi
}

# ==========================================================
# start database into ADMIN mode
# ==========================================================
start_lc_admin () {
    echo starting $LC into ADMIN | tee -a $LOGFILE

    $DBMCLI db_admin >> $LOGFILE
    rc=$?

    if [ $rc = 0 ]
    then
        STATE=ADMIN
    else
        end_error
    fi
}

# ==========================================================
# start database into ADMIN mode (SLOW)
# ==========================================================
start_slow () {
    echo starting $LC \(SLOW KERNEL\) into ADMIN | tee -a $LOGFILE

    $DBMCLI db_admin -slow >> $LOGFILE
    rc=$?

    if [ $rc = 0 ]
    then
        STATE=ADMIN
    else
        end_error
    fi
}

# ==========================================================
# restart of the database
# ==========================================================
start_lc_online () {
    echo starting $LC into ONLINE | tee -a $LOGFILE

    $DBMCLI db_online >> $LOGFILE
    rc=$?

    if [ $rc != 0 ]
    then
        echo
        echo restart not possible \(please check knldiag\) | tee -a $LOGFILE
        end_error
    fi
}

# ==========================================================
# restart the database
# ==========================================================
restart_lc () {
    echo restarting $LC  | tee -a $LOGFILE

    $DBMCLI db_restart >> $LOGFILE
    rc=$?

    if [ $rc != 0 ]
    then
        end_error
    fi
}

# ==========================================================
# stop the database
# ==========================================================
stop_lc () {
    echo stopping $LC  | tee -a $LOGFILE

    $DBMCLI $1 >> $LOGFILE
    rc=$?

    if [ $rc != 0 ]
    then
        end_error
    fi
}

# ==========================================================
# INIT CONFIG
# ==========================================================
init_config () {
    echo starting INIT CONFIG | tee -a $LOGFILE

    $DBMCLI -uUTL -c util_execute init config >> $LOGFILE
    rc=$?

    if [ $rc != 0 ]
    then
        end_error
    fi
}

# ==========================================================
# ACTIVATE SERVERDB
# ==========================================================
activate_serverdb () {
    echo starting ACTIVATE SERVERDB | tee -a $LOGFILE

    $DBMCLI -uUTL -c util_activate $dba_user,$dba_pwd >> $LOGFILE
    rc=$?

    if [ $rc != 0 ]
    then
        end_error
    fi
}

# ==========================================================
# loading SYSTEM TABLES
# ==========================================================
load_sys_tables () {
    echo loading SYSTEM TABLES | tee -a $LOGFILE

    $DBMCLI -c load_systab -ud $domain_pwd >> $LOGFILE
    rc=$?

    if [ $rc != 0 ]
    then
        end_error
    fi
}

# ==========================================================
# creating SAP user 
# ==========================================================
create_user () {
    echo CREATING USER $1 | tee -a $LOGFILE

    $DBMCLI -uSQL $dba_user,$dba_pwd sql_execute \
             create user $1 password $2 dba not exclusive >> $LOGFILE
    rc=$?

    if [ $rc != 0 ]
    then
        end_error
    fi
}

# ==========================================================
# get extension of shared library
# ==========================================================
get_sl_ext () {

    case $OS in

        HP-UX)
            SL_EXT=sl
            ;;

        SunOS | OSF1 | AIX | Linux | SINIX* | Reliant*)
            SL_EXT=so
            ;;

        Windows_NT)
            SL_EXT=dll
	    ;;

        *)
            SL_EXT=o
            ;;

    esac
}


# ==========================================================
# registration COM routines
# ==========================================================
register_COM () {

    if [ $OS = "Windows_NT" ]
    then
        inst_path=$INSTROOT\\sap\\
    else
        inst_path=$INSTROOT/sap/
    fi

    get_sl_ext
    echo

    #-------------------------------------------------------------------- 
    # list of the application modules
    #-------------------------------------------------------------------- 

    if [ $OS = "Windows_NT" ]
    then
    	APPL_COM='sapapo sapatp saprpm sapts saprep sapsea sphsapdb'
    else
    	APPL_COM='libSAPAPO libSAPATP libSAPRPM libSAPTS libSAPREP libSAPSEA sphsapdb'
    fi

    #-------------------------------------------------------------------- 

    for f in $APPL_COM
    do
        if [ -r $inst_path$f.$SL_EXT ]
        then
            echo registration of $inst_path$f.$SL_EXT | tee -a $LOGFILE

            $REGCOM $inst_path$f >> $LOGFILE
            rc=$?

            if [ $rc != 0 ]
            then
                end_error
            fi
        fi
    done
}

# ==========================================================
# creation of COM routines
# ==========================================================
create_COM () {
    echo
    echo creating COM routines | tee -a $LOGFILE

    $DBMCLI exec_load $dba_user,$dba_pwd lapps.py \"-usap $sap_user,$sap_pwd\" >> $LOGFILE
    rc=$?

    if [ $rc != 0 ]
    then
        end_error
    fi
}

# ==========================================================
# nothing todo
# ==========================================================
nothing_todo () {
    echo
    echo $DBTEXT2 $LC is already $STATE | tee -a $LOGFILE
    save_history
    exit 0
}

# ==========================================================
# save logfile into a history file
# ==========================================================
save_history () {
    echo '------------------------------------------------------------' >> $LOGFILE
    echo `date` >> $LOGFILE
    echo '************************** END *****************************' >> $LOGFILE

    cat $LOGFILE >> $HISFILE
}


# ==========================================================
# call user exit function (script param1 param2)
# ==========================================================
call_user_exit () {
    if [ -x $1 ]
    then
        echo
        echo calling $1 $2 $3 | tee -a $LOGFILE
        $1 $2 $3
        echo
    fi
}

# ==========================================================
# inform the cluster software
# mode : starting, stopping
# action : req, ok, error
# ==========================================================
cluster_info () {
    if [ $CLUST_MODE != "NO_INFO" ]
    then
        call_user_exit $LCCLUSTER $CLUST_MODE $1
    fi
}

# ==========================================================
# errorexit
# ==========================================================
errorexit () {
    echo $1
    exit 1
}

# ==========================================================
# end with error
# ==========================================================
end_error () {
    cluster_info error
    echo
    echo ERROR : $DBTEXT2 $LC not $DONETXT \(see $LOGFILE\) | tee -a $LOGFILE
    save_history
    exit 1
}

# ==========================================================
# end without error
# ==========================================================
end_ok () {
    cluster_info ok
    echo
    echo $DBTEXT2 $LC successfully $DONETXT | tee -a $LOGFILE
    save_history
    exit 0
}

#########################################################################
#
# main program
#
#########################################################################

    if [ $# -gt 0 ] 
    then
        LC=$1
    else
        usage
        errorexit ""
    fi

    OS=`uname`

    mode=restart

    #----------------------- internal user/pwd --------------------------

    db_user=control
    db_pwd=control
    dba_user=superdba
    dba_pwd=admin
    sap_user=sapr3
    sap_pwd=sap
    domain_pwd=domain

    #-----------------------check input parameters -----------------------

    while [ $# -gt 1 ]; do
        case $2 in

            -uDBM)
                db_user=`echo $3 | awk '{split($0,a,","); print a[1]}'`
                db_pwd=`echo $3 | awk '{split($0,a,","); print a[2]}'`
                shift;;

            -uDBA)
                dba_user=`echo $3 | awk '{split($0,a,","); print a[1]}'`
                dba_pwd=`echo $3 | awk '{split($0,a,","); print a[2]}'`
                shift;;

            -uSQL)
                sap_user=`echo $3 | awk '{split($0,a,","); print a[1]}'`
                sap_pwd=`echo $3 | awk '{split($0,a,","); print a[2]}'`
                shift;;

            -ud)
                domain_pwd=$3
                shift;;

            *)
                mode=$2
                ;;
        esac

        shift
    done

    #-------------------------- dbmcli -----------------------------------

    DBMCLI="dbmcli -d $LC -u $db_user,$db_pwd"

    #------------------------ check database ----------------------------

    dbstate=`$DBMCLI show state`
    rc=$?

    if [ $rc != 0 ]
    then
        echo $dbstate
        errorexit "ERROR : could not connect to $LC" 
    fi

    #---------------------- get installation directory ------------------

    get_instroot

    #-------------------------- register tools ---------------------------

    REGCOM="$INSTROOT/bin/xregcomp -c"
    LCCLUSTER="$INSTROOT/sap/lccluster"

    LOGFILE=$INSTROOT/lcinit.log
    HISFILE=$INSTROOT/lcinit.his

    #---------------------- check instance type -------------------------

    check_dbtype

    if [ $INSTTYPE = "LVC" ]
    then
        DBTEXT1=LIVECACHE
        DBTEXT2=liveCache
    else
        DBTEXT1=DATABASE
        DBTEXT2=Database
    fi

    #--------------------- cluster start/stop mode ----------------------

    clust_start=starting
    clust_stop=stopping
    CLUST_MODE=NO_INFO

    #----------------------- print out the header -----------------------

    echo
    echo '************************* START ****************************' > $LOGFILE
    echo $DBTEXT1 $LC \($mode\) | tee -a $LOGFILE
    echo `date` >> $LOGFILE
    echo '------------------------------------------------------------' >> $LOGFILE
    echo installation path: $INSTROOT >> $LOGFILE
    echo operating system : $OS >> $LOGFILE
    echo

    #--------------------- check state of the database ------------------
    check_state
    echo The database state is $STATE

    #----------------------- init of the database -----------------------

    if [ $mode = "init" -o $mode = "INIT" ]
    then
        DONETXT=initialized

        if [ $STATE != OFFLINE ]
        then
            CLUST_MODE=$clust_stop
            cluster_info req

            stop_lc db_stop

            cluster_info ok
        fi

        CLUST_MODE=$clust_start
        cluster_info req

        start_lc_admin
        check_version

        init_config
        activate_serverdb
        load_sys_tables

        create_user $sap_user $sap_pwd

        restart_lc

        register_COM
        create_COM

        end_ok
    fi

    #---------------------- restart of the database ---------------------

    if [ $mode = "restart" -o $mode = "RESTART" -o $mode = "slow" ]
    then
        DONETXT=restarted
        if [ $STATE = "ONLINE" ]
        then
            nothing_todo
        fi

        CLUST_MODE=$clust_start
        cluster_info req

        if [ $STATE = "OFFLINE" ]
        then
            if [ $mode = "slow" ]
            then
                start_slow
            else
                start_lc_admin
            fi
        fi

        check_version

        start_lc_online

        register_COM
        create_COM

        end_ok
    fi

    #------------------------- stop the database ------------------------

    if [ $mode = "stop" -o $mode = "STOP" ]
    then
        DONETXT=stopped

        if [ $STATE = "OFFLINE" ]
        then
            nothing_todo
        fi
    
        CLUST_MODE=$clust_stop
        cluster_info req

        check_version
    
        stop_lc db_stop

        end_ok
    fi

    #----------------------- shutdown the database ----------------------

    if [ $mode = "shutdown" -o $mode = "SHUTDOWN" ]
    then
        DONETXT=stopped

        if [ $STATE = "OFFLINE" ]
        then
            nothing_todo
        fi

        CLUST_MODE=$clust_stop
        cluster_info req

        check_version

        stop_lc db_offline

        end_ok
    fi

    #----------------------- register COM routines ----------------------

    if [ $mode = "register" -o $mode = "REGISTER" ]
    then
        DONETXT=registered
        if [ $STATE != "ONLINE" ]
        then
            CLUST_MODE=$clust_start
            cluster_info req

            start_lc_online
            check_version
        else
            CLUST_MODE=NO_INFO
            check_version
        fi

        register_COM
        create_COM

        end_ok
    fi

    exit 0

#########################################################################
