#!/bin/bash

. ./param_bash.ini
PROMPT_FOR_COPY_NUM()
{
    echo -n "Please enter a slot number (1-9) ${SOFT_DIR}[$SLOT_NUMBER]:"
    read ans
    if [ "$ans" != "" ] ; then
        SLOT_NUMBER=$ans
    fi
}
CHECK_VALID_COPY()
{
    ls -l $APP_HOME | grep d4_$SLOT_NUMBER > /dev/null
    if [ "$?" = "0" ] ; then
        INFORM "The selected slot is already occupied by a different Rosetta installation"
        INFORM "Would you like to continue[Y] or to choose a diffrent slot[n]"
        CONFIRM
        if [ "$?" = "0" ] ; then
            return 0
        else
            PROMPT_FOR_COPY_NUM
            CHECK_VALID_COPY
        fi
    else
        return 0
    fi
}

clear

if [ "${INST_TYPE}" = "DB_ONLY" ] ; then
    CANCEL "The installation type doesn't require Rosetta SW extraction" "$0"
fi

START "Extracting Rosetta software" "$0"
if [ ! -w /etc/passwd ] && [ "$USER" != "$MAIN_USER" ] ; then
    ERROR "please run the script as $MAIN_USER user or root user" "$0"
fi

MainUserExist
if [ "$?" = "1" ] ; then 
    ERROR "$MAIN_USER user doesn't exist" "ikit_5_1"
fi

if [ ! -d ${APP_HOME} ] ; then 
    ERROR "Required Directories are missing, please run ikit_2_6" "ikit_5_1"
fi 

echo -n "Please enter the location of the Rosetta Binaries [$IKIT_FTP_DIR] : "
read ans
if [ "$ans" != "" ] ; then
    IKIT_FTP_DIR=$ans
fi
if [ ! -f $IKIT_FTP_DIR/$VER.tar.gz_aa ] ; then
    ERROR "the package $IKIT_FTP_DIR/$VER.tar.gz does not exist" "ikit_5_1"
fi

if [  -w /etc/passwd ] ; then
    su $param_to_su ${MAIN_USER} -c "touch $IKIT_FTP_DIR/test" > /dev/null 2>&1
else
    touch $IKIT_FTP_DIR/test > /dev/null 2>&1
fi
if [ "$?" != "0" ] ; then
    ERROR "you do not have write permissions in the $IKIT_FTP_DIR directory as user $MAIN_USER"
else
    rm -f $IKIT_FTP_DIR/test
fi
PROMPT_FOR_COPY_NUM
CHECK_VALID_COPY
ret=$?
while [ "$ret" -eq "1" ] ; do
    CHECK_VALID_COPY
    ret=$?
done
Update_params "SLOT_NUMBER" "${SLOT_NUMBER}"
########################su to aleph###########################################
WAIT "Creating $APP_HOME/$SOFT_DIR$SLOT_NUMBER"
if [ -w /etc/passwd  ] ; then
    su $param_to_su $MAIN_USER -c "bash extract_dps_sw.bash"
else
    bash extract_dps_sw.bash
fi 
###############################################################################
if [ "$?" = "0" ] ; then 
	cat $IKIT_DIR/header.dat.tml | \
        sed -e "s:@EXL_DIR:${APP_HOME}/${SOFT_DIR}${SLOT_NUMBER}:" | \
        sed -e "s:@ORACLE_SID:$ORACLE_SID:" \
        > $IKIT_DIR/header.dat

	Update_params "SLOT_NUMBER" "${SLOT_NUMBER}"
	INFORM "Fixing Rosetta home permissions"
        chown -Rh $MAIN_USER:$GROUP ${APP_HOME}/${SOFT_DIR}${SLOT_NUMBER} > /dev/null 2>&1
        DONE "The Rosetta software extracted properly" "ikit_5_1"
else
	ERROR "failed to extract PDS software" "ikit_5_1"
fi
