#!/bin/sh

# permission check
id | grep uid=0 > /dev/null
if [ $? -ne 0 ]; then
  echo "Please execute by root user."
  echo
  exit 1;
fi

# variables
setup_path=`echo $0 | sed s/setup.sh//g`
if [ -z ${setup_path} ]; then
    setup_path="./"
fi
product="Universal RAID Utility";
uru_package="UniversalRaidUtility-4.03-0.i386.*rpm";
slib_package="storelib-4.14-0.i386.rpm"
wpp_package="WebPAMPRO_Agent-3.15.0070-*.i386.rpm"
installver="4.03";
storelibver="4.14";
wppver="3.15.0070";

uru_update=0;
uru_oldver=0;

declare -i errcode;
errcode=0;

update_tmpdir="/tmp/uraidutl_setup/"
export AXIS2C_HOME="/opt/nec/axis2c"

usage_message="usage: setup.sh --install [--reptbljp | --reptblen]\n\
       setup.sh --nomgr [--reptbljp | --reptblen]\n       setup.sh --uninstall"

CRONFILE=/var/spool/cron/root
if [ -f /etc/SuSE-release ]; then
    CRONFILE=/var/spool/cron/tabs/root
fi

# verCompare - compare $1 and $2
# return value:  2 when $1 > $2
#                1 when $1 = $2
#                0 when $1 < $2
verCompare(){
    arg1major=`echo $1 | cut -d . -f 1`;
    arg1minor=`echo $1 | cut -d . -f 2`;
    arg1rev=`echo $1 | cut -d . -f 3`;
    arg2major=`echo $2 | cut -d . -f 1`;
    arg2minor=`echo $2 | cut -d . -f 2`;
    arg2rev=`echo $2 | cut -d . -f 3`;

    if [ -z $arg1rev ]; then
        arg1rev=0;
    fi
    if [ -z $arg2rev ]; then
        arg2rev=0;
    fi

    if [ $arg1major -gt $arg2major ]; then
        return 2;
    elif [ $arg1major -lt $arg2major ]; then
        return 0;
    else
        if [ $arg1minor -gt $arg2minor ]; then
            return 2;
        elif [ $arg1minor -lt $arg2minor ]; then
            return 0;
        else
            if [ $arg1rev -gt $arg2rev ]; then
                return 2;
            elif [ $arg1rev -lt $arg2rev ]; then
                return 0;
            else
                return 1;
            fi
        fi
    fi
}

# needToInstallUru - make decision to install Universal RAID Utility
# return value: 1 -> need to install Universal RAID Utility
#               0 -> doesn't need to install Universal RAID Utility
needToInstallUru(){
    rpm -q UniversalRaidUtility >& /dev/null
    if [ $? = 0 ]; then    
        echo "        Setup error: Universal RAID Utility has been already installed.";
        echo "        Please uninstall existing version to install this version.";
        return 0;
    fi
    return 1; # first installation
}

# needToInstallStoreLib - make decision to install Storelib
# return value: 1 -> need to install StoreLib 
#               2 -> need to update StoreLib
#               0 -> doesn't need to install StoreLib 
needToInstallStoreLib(){
    # check whether this system is VMware ESX 4
    uname -r | grep "^2\.6.*ESX$" >& /dev/null
    if [ $? = 0 ]; then
        return 0;
    fi
    # check whether StoreLib is installed
    if [ -f /usr/lib/libstorelib.so ]; then
        # read symbolic link recursively
        currentver=`readlink -f /usr/lib/libstorelib.so`;
        # cut "/usr/lib/libstorelib.so"
        currentver=`echo $currentver | cut -c 25-`;
        # cur after "-"
        currentver=`echo $currentver | cut -d - -f 1`;
        verCompare $storelibver $currentver;
        if [ $? -lt 1 ]; then
            return 0;
        else
            return 2; # update installation
        fi
    fi
    return 1; # first installation
}

# needToInstallWPPAgent - make decision to install WPPAgent
# return value: 1 -> need to install WPPAgent
#               2 -> need to update WPPAgent
#               0 -> doesn't need to install WPPAgent
needToInstallWPPAgent(){
    # check whether WPPAgent is installed
    rpm -q WebPAMPRO_Agent >& /dev/null
    if [ $? -eq 0 ]; then
        # rpm wppagent ver
        currentver=`rpm -q WebPAMPRO_Agent`;
        # cut "-"
        currentver=`echo $currentver | cut -d - -f 2`;
        verCompare $wppver $currentver;
        if [ $? -lt 1 ]; then
            return 0;
        else
            return 2; # update installation
        fi
    fi
    return 1; # first installation
}

# SelectReptbl $# $2
# return value: 1 -> Selected Reptbl
#               2 -> No select Reptbl option
#               0 -> Option error
selectReptbl(){
    if [ $1 -eq 1 ]; then
        return 2;
    elif [ $1 -ge 2 ]; then
        case "$2" in
            --reptbljp)
                echo ja > /var/tmp/reptbl.tmp; # Set Japanese
                ;;
            --reptblen)
                echo en > /var/tmp/reptbl.tmp; # Set English
                ;;
            *)
                return 0; # second option error
                ;;
        esac
    else
        return 0; # too much options
    fi
    return 1;
}

# chkRaidctrl
# return value: 1 -> storelib
#               2 -> WebPAMPRO
#               3 -> storelib & WebPAMPRO
#               0 -> none vender api
chkRaidctrl(){
    lsi_flg=1
    promise_flg=1
    alcor_flg=1
    drake_flg=1
    merga_flg=1
    fury_flg=1

    ### Foxcove or N8103-116/117/118 ###
    lspci -n | grep '1000:0060'  > /dev/null
    ruchbah_flg=$?

    ### N8103-130 ###
    lspci -n | grep '1000:0079'  > /dev/null
    castor_flg=$?

    ### N8103-149/150/151/160 ###
    lspci -n | grep '1000:005b'  > /dev/null
    alcor_flg=$?

	### N8103-(G)171(Drake) ###
    lspci -n | grep '1000:0073'  > /dev/null
    drake_flg=$?

	### Merga, Seginus ###
    lspci -n | grep '1000:005d'  > /dev/null
    merga_flg=$?

	### Fury ###
    lspci -n | grep '1000:005f'  > /dev/null
    fury_flg=$?

    ### Yamato2 ###
    lspci -v -n | grep '1000:0411' -A 1 | awk '(NR % 3 == 1){ prevline = $0} (NR % 3 == 2){ print prevline $0}' | grep '1033:8287' > /dev/null
    yamato2_flg=$?

    ### N8103-109 ###
    lspci -v -n | grep '105a:8650' -A 1 | awk '(NR % 3 == 1){ prevline = $0} (NR % 3 == 2){ print prevline $0}' | grep '105a:4601' > /dev/null
    n8103_109_flg=$?

    ### STEX8760 Series ###
    lspci -v -n | grep '105a:8760' > /dev/null
    STEX8760_flg=$?

    ### N8103-90 ###
    n8103_90_flg=1
    lspci -v -n | grep '1000:0411' -A 1 | awk '(NR % 3 == 1){ prevline = $0} (NR % 3 == 2){ print prevline $0}' | grep '1000:1002' > /dev/null
    if [ $? -eq 0 ]; then
        # check on board chip's subsystemID
        while read fn
        do
        lspci -n -v | grep Subsystem | grep `echo $fn | cut -f 1 -d " "` > /dev/null
        n8103_90_flg=$?
        if [ $n8103_90_flg -eq 0 ]; then
            break
        fi
        done < ${setup_path}subsys.txt
    fi

    if [ $fury_flg -eq 0 ] || [ $merga_flg -eq 0 ] || [ $drake_flg -eq 0 ] || [ $alcor_flg -eq 0 ] || [ $castor_flg -eq 0 ] || [ $ruchbah_flg -eq 0 ] || [ $yamato2_flg -eq 0 ] || [ $n8103_90_flg -eq 0 ]; then
        lsi_flg=0
    fi

    if [ $n8103_109_flg -eq 0 ] || [ $STEX8760_flg -eq 0 ]; then
        promise_flg=0
    fi

    if [ $lsi_flg -eq 0 ] && [ $promise_flg -ne 0 ]; then
        return 1;
    elif [ $lsi_flg -ne 0 ] && [ $promise_flg -eq 0 ]; then
        return 2;
    elif [ $lsi_flg -eq 0 ] && [ $promise_flg -eq 0 ]; then
        return 3;
    else
        echo "Cannot detect the supported RAID Controller.";
        echo "Installation aborted.";
        return 0;
    fi

}

# installEciService
# return value: 0 -> Install Success
#               2 -> Install Failure
installEciService(){

    # check EciService installed
    rpm -qa | grep eciservice >& /dev/null
    if [ $? -eq 0 ]; then
        sh ${AXIS2C_HOME}/bin/eci_stop.sh;
    fi

    # Install EciService
    currentDir=`pwd`;
    cd ${setup_path}/eci;
    sh eciservice-*.sh -si;
    ret=$?;
    cd ${currentDir};

    return $ret;
}

# uninstallEciService
# return value: 0 -> Uninstall Success
#               1 -> other Service use EciService (Uninstall Failure)
#               2 -> Uninstall Failure
uninstallEciService(){

    ret=0;

    # check EciService installed
    rpm -qa | grep eciservice >& /dev/null
    if [ $? -eq 0 ]; then
        sh ${AXIS2C_HOME}/bin/eci_stop.sh;

        # Uninstall EciService
        currentDir=`pwd`;
        cd ${setup_path}/eci;
        sh eciservice-*.sh -su;
        ret=$?;
        cd ${currentDir};
    fi

    return $ret;
}

# chkPackages
chkPackages(){
    # check connected RAID controller
    chkRaidctrl;
    raid_flg=$?;
    
    if [ ${raid_flg} -eq 0 ]; then
        exit 1;
    fi

    # check uru_package
    ls ${setup_path}${uru_package} > /dev/null 2>&1
    if [ $? -ne 0 ]; then
        errcode=$errcode+1;
    fi

    # check slib_package
    ls ${setup_path}${slib_package} > /dev/null 2>&1
    if [ $? -ne 0 ] && ( [ ${raid_flg} -eq 1 ] || [ ${raid_flg} -eq 3 ] ); then
        errcode=$errcode+4;
    fi

    # check wpp_package
    ls ${setup_path}${wpp_package} > /dev/null 2>&1
    if [ $? -ne 0 ] && ( [ ${raid_flg} -eq 2 ] || [ ${raid_flg} -eq 3 ] ); then
        errcode=$errcode+8;
    fi

    # check eci_package
    ls ${setup_path}/eci/eciservice-*.rpm > /dev/null 2>&1
    if [ $? -ne 0 ] && [ "$1" != "--nomgr" ]; then
        errcode=$errcode+16;
    fi
}

# parse argument
case "$1" in
  --install | --nomgr)
    # check Packages
    chkPackages $1;
    if [ ${errcode} -ne 0 ]; then
        printf 'Setup error: (errcode: 0x%02x)\n' ${errcode};
        exit 1;
    fi
    
    # check ExpressUpdate
    if [ "$2" == "--eua" ]; then
        # EUA install
        export URUexpressUpdate=1;
        # SelectReptbl
        selectReptbl 1;
    elif [ "$3" == "--eua" ]; then
        # EUA Update
        export URUtranscfg=1;
        export URUexpressUpdate=1;
        # SelectReptbl
        selectReptbl 2 $2;
    else
        # SelectReptbl
        selectReptbl $# $2;
    fi

    if [ $? -eq 0 ]; then
        echo -e "${usage_message}";
        exit 1;
    fi

    # check whether utility is installed
    needToInstallUru;
    if [ $? -eq 0 ]; then
        exit 1; # already installed
    fi

    echo "Installing ${product}...";

    # EciService Install
    if [ "$1" != "--nomgr" ]; then
        installEciService;
    else
        export URUnomgr=1;
    fi

    # check connected RAID controller
    chkRaidctrl;
    raid_flg=$?;

    # check whether StoreLib is installed
    if [ $raid_flg -eq 1 ] || [ $raid_flg -eq 3 ]; then
        needToInstallStoreLib;
        case $? in
        1)  # first install
            rpm -ivh ${setup_path}${slib_package};
            ;;

        2)  # update install (uninstall & install)
            rpm -e storelib
            rpm -q Lib_Utils >& /dev/null
            if [ $? -eq 0 ]; then
                rpm -e Lib_Utils
            fi
            rpm -ivh ${setup_path}${slib_package};
            ;;
        esac
    else
        rpm -q storelib >& /dev/null
        if [ $? -eq 0 ]; then
            rpm -e storelib
        fi
        rpm -q Lib_Utils >& /dev/null
        if [ $? -eq 0 ]; then
            rpm -e Lib_Utils
        fi
    fi

    # check whether WPPAgent is installed
    if [ $raid_flg -eq 2 ] || [ $raid_flg -eq 3 ]; then
        needToInstallWPPAgent;
        case $? in
            1)  # first install
                rpm -ivh ${setup_path}${wpp_package};
                ;;

            2)  # update install (uninstall & install)
                rpm -e WebPAMPRO_Agent
                rpm -ivh ${setup_path}${wpp_package};
                ;;
        esac
    else
        rpm -q WebPAMPRO_Agent >& /dev/null
        if [ $? -eq 0 ]; then
            rpm -e WebPAMPRO_Agent
        fi
    fi

    if [ ${uru_oldver} -eq 1 ] || [ ${raid_flg} -eq 0 ]; then
        exit 0;
    fi

    # install Universal RAID Utility
    rpm -ivh ${setup_path}${uru_package};
    # sleep 3 seconds to wait service starts
    sleep 3
    rm -f /var/tmp/reptbl.tmp >& /dev/null

    # Update by ExpressUpdate
    if [ -n "$URUtranscfg" ]; then
        # copy raidcmd.tmp
        cp -p /opt/nec/raidcmd/raidcmd.tmp.backup /opt/nec/raidcmd/raidcmd.tmp >& /dev/null

        # load setting
        /lib/ld-linux.so.* ${setup_path}transcfg --load
        errcode=$?
        if [ ${errcode} -ne 0 ]; then
            echo "The error occurred during transferring settings. (errcode: ${errcode})"
            echo "Please reconfigure manually using backup file whose name added \".backup.\""
        else
            # remove backup files
            rm -rf /etc/opt/nec/raidsrv/raidsrv.conf.backup >& /dev/null
            rm -rf /etc/opt/nec/raidsrv/raidapi.conf.backup >& /dev/null
            rm -rf /etc/opt/nec/raidsrv/raidsrv_agent.conf.backup >& /dev/null
            rm -rf /etc/opt/nec/raidsrv/raidconn-storelib.conf.backup >& /dev/null
            rm -rf /etc/opt/nec/raidsrv/raidconn-i2api.conf.backup >& /dev/null
            rm -rf /etc/opt/nec/raidcmd/raidcmd.conf.backup >& /dev/null
            rm -rf /opt/nec/raidcmd/raidcmd.tmp.backup >& /dev/null
        fi
    fi

    # delete workdir
    rm -rf ${update_tmpdir}
    ;;

  --uninstall)
    echo "Uninstalling ${product}...";

    # uninstall by ExpressUpdate
    if [ "$2" == "--eua" ]; then
        export URUexpressUpdate=1;
        # create workdir
        mkdir -p ${update_tmpdir}

        # backup cron
        cp -p $CRONFILE /var/tmp/root.eua.backup
        
        # back up conf files
        cp -p /etc/opt/nec/raidsrv/raidsrv.conf /etc/opt/nec/raidsrv/raidsrv.conf.backup >& /dev/null
        cp -p /etc/opt/nec/raidsrv/raidapi.conf /etc/opt/nec/raidsrv/raidapi.conf.backup >& /dev/null
        cp -p /etc/opt/nec/raidsrv/raidsrv_agent.conf /etc/opt/nec/raidsrv/raidsrv_agent.conf.backup >& /dev/null
        cp -p /etc/opt/nec/raidsrv/raidconn-storelib.conf /etc/opt/nec/raidsrv/raidconn-storelib.conf.backup >& /dev/null
        cp -p /etc/opt/nec/raidsrv/raidconn-i2api.conf /etc/opt/nec/raidsrv/raidconn-i2api.conf.backup >& /dev/null
        cp -p /etc/opt/nec/raidcmd/raidcmd.conf /etc/opt/nec/raidcmd/raidcmd.conf.backup >& /dev/null
        cp -p /opt/nec/raidcmd/raidcmd.tmp /opt/nec/raidcmd/raidcmd.tmp.backup >& /dev/null
        
        # correct settings
        /lib/ld-linux.so.* ${setup_path}transcfg --save
        errcode=$?
        if [ ${errcode} -ne 0 ]; then
            echo "The error occurred during transferring settings."
            echo "Please reconfigure manually using backup file whose name added \".backup.\""
        fi
    fi
    
    # uninstall Universal RAID Utility
    rpm -e UniversalRaidUtility
    if [ $? -ne 0 ]; then
        # error occurred
        echo "Setup error: Uninstalling package UniversalRaidUtility is failed."
        exit 1;
    fi

    # restore cron
    if [ "$2" == "--eua" ]; then
        mv /var/tmp/root.eua.backup $CRONFILE
    fi

    # uninstall StoreLib
    rpm -q storelib >& /dev/null
    if [ $? -eq 0 ]; then
        rpm -e storelib
        if [ $? -ne 0 ]; then
            # error occurred
            echo "Setup error:  Failed to uninstall storelib package but"\
               "UniversalRaidUtility package is already uninstalled successfully."
        fi
    fi
    rpm -q Lib_Utils >& /dev/null
    if [ $? -eq 0 ]; then
        rpm -e Lib_Utils
        if [ $? -ne 0 ]; then
            # error occurred
            echo "Setup error:  Failed to uninstall Lib_Utils package but"\
                "UniversalRaidUtility package is already uninstalled successfully."
        fi
    fi

    # uninstall WppAgent
    rpm -q WebPAMPRO_Agent >& /dev/null
    if [ $? -eq 0 ]; then
        rpm -e WebPAMPRO_Agent
        if [ $? -ne 0 ]; then
            # error occurred
            echo "Setup error:  Failed to uninstall WebPAMPRO_Agent package but"\
                "UniversalRaidUtility package is already uninstalled successfully."
        fi
    fi
    # uninstall EciService
    uninstallEciService;
    ;;

  --force-install)    
    # SelectReptbl
    selectReptbl $# $2;
    if [ $? -eq 0 ]; then
        echo -e "${usage_message}";
        exit 1;
    fi

    # uninstall Universal RAID Utility
    rpm -q UniversalRaidUtility >& /dev/null
    if [ $? -eq 0 ]; then
        rpm -e UniversalRaidUtility
        if [ $? -ne 0 ]; then
            # error occurred
            echo "Setup error: Uninstalling package UniversalRaidUtility is failed."
            exit ;
        fi
    fi

    # uninstall StoreLib
    rpm -q storelib >& /dev/null
    if [ $? -eq 0 ]; then
        rpm -e storelib
        if [ $? -ne 0 ]; then
            # error occurred
            echo "Setup error:  Failed to uninstall storelib package but"\
                "UniversalRaidUtility package is already uninstalled successfully."
        fi
    fi
    rpm -q Lib_Utils >& /dev/null
    if [ $? -eq 0 ]; then
        rpm -e Lib_Utils
        if [ $? -ne 0 ]; then
            # error occurred
            echo "Setup error:  Failed to uninstall Lib_Utils package but"\
                "UniversalRaidUtility package is already uninstalled successfully."
        fi
    fi

    # uninstall WppAgent
    rpm -q WebPAMPRO_Agent >& /dev/null
    if [ $? -eq 0 ]; then
        rpm -e WebPAMPRO_Agent
        if [ $? -ne 0 ]; then
            # error occurred
            echo "Setup error:  Failed to uninstall WebPAMPRO_Agent package but"\
                "UniversalRaidUtility package is already uninstalled successfully."
        fi
    fi

    # uninstall EciService
    uninstallEciService;

    # force install (there's no support)
    echo "Force installing ${product}...";
    installEciService;
    rpm -ivh ${setup_path}${slib_package};
    rpm -ivh ${setup_path}${wpp_package};
    rpm -ivh ${setup_path}${uru_package};
    # sleep 3 seconds to wait service starts
    sleep 3
    rm -f /var/tmp/reptbl.tmp >& /dev/null
    ;;

  --utilityonly-uninstall)
    # partly uninstall (there's no support)
    echo "Partly uninstalling ${product}...";
    rpm -e UniversalRaidUtility
    if [ $? -ne 0 ]; then
        # error occurred
        echo "Uninstalling package UniversalRaidUtility failed"
        exit 1;
    fi

    ;;
  --version)
    echo "Universal RAID Utility installer Ver ${installver}";
    ;;
  *)
    echo -e "${usage_message}";
    ;;
esac

