#!/bin/sh

##
# Defining different exit codes. This would help track failures better
##

# Exit code table
E_SUCCESS=0
E_GENERIC_FAILURE=1
E_OS_NOT_SUPPORTED=25
E_SETUP_ARG_MISSING=65
E_SETUP_DIRCREATION_FAILURE=66
E_SETUP_CHANGEDIR_FAILURE=67
E_CHECKOUT_ARG_MISSING=75
E_CHECKOUT_SOURCE_DIR_NOT_FOUND=76
E_CHECKOUT_FAILURE=77
E_BUILD_INCORRECT_ARG=95
E_BUILD_INMSYNC_FAILURE=96
E_BUILD_INMSYNC_DIR_NOT_FOUND=97
E_BUILD_SVFRD_FAILURE=98
E_BUILD_SOURCE_DIR_NOT_FOUND=99
E_BUILD_UNREG_FAILURE=100
E_BUILD_ALERT_FAILURE=101
E_BUILD_DSPACE_FAILURE=102
E_BUILD_VACP_FAILURE=103
E_VERSION_ARG_MISSING=85
E_VERSION_BRANCH_MISMATCH=86
E_VERSION_BIN_DIR_NOT_FOUND=87
E_VERSION_DCAL_NOT_FOUND=88
E_PACKAGING_BINARIES_ABSENT=105
E_PACKAGING_PARTNER_DIR_ABSENT=106

##
# This function executes a command and logs the output
##
DO_AND_LOG()
{
	CMD=$1
	eval $CMD >> $FLOG
}

##
# This function verifies the exit status of a program and print messages accordingly
##
VERIFY()
{
	status=$1

	case $status in

		$E_SUCCESS) ;;

                $E_GENERIC_FAILURE)
                        echo "FAILURE WHILE BUILDING. PLEASE SEE ERROR MESSAGES ABOVE!"
                        exit $E_GENERIC_FAILURE ;;

                $E_OS_NOT_SUPPORTED)
                        echo "THIS PLATFORM IS NOT SUPPORTED YET!"
                        exit $E_OS_NOT_SUPPORTED ;;

		$E_SETUP_ARG_MISSING)
		   	echo "SOME OR ALL ARGUMENTS FOR fx_bld_env_setup.sh ARE MISSING!"
			exit $E_SETUP_ARG_MISSING ;;

		$E_SETUP_DIRCREATION_FAILURE)
			echo "DIRECTORY $TOP_BLD_DIR COULD NOT BE CREATED!"
			exit $E_SETUP_DIRCREATION_FAILURE ;;

		$E_SETUP_CHANGEDIR_FAILURE)
			echo "FAILED TO CHANGE DIRECTORY TO $TOP_BLD_DIR!"
			exit $E_SETUP_CHANGEDIR_FAILURE ;;

		$E_CHECKOUT_SOURCE_DIR_NOT_FOUND)
			echo "DIRECTORY source NOT FOUND UNDER TOP BUILD DIRECTORY!"
			exit $E_CHECKOUT_SOURCE_DIR_NOT_FOUND ;;

		$E_CHECKOUT_ARG_MISSING)
			echo "SOME OR ALL ARGUMENTS FOR fx_checkout.sh ARE MISSING!"
			exit $E_CHECKOUT_ARG_MISSING ;;

		$E_CHECKOUT_FAILURE)
			echo "CVS CHECKOUT FAILED FOR SOME FILES!"
			exit $E_CHECKOUT_FAILURE ;;

		$E_BUILD_INCORRECT_ARG)
			echo "INCORRECT ARGUMENTS FOR fx_bld.sh!"
			exit $E_BUILD_INCORRECT_ARG ;;

		$E_BUILD_INMSYNC_DIR_NOT_FOUND)
			echo "DIRECTORY host/inmsync NOT FOUND UNDER source DIRECTORY!"
			exit $E_BUILD_INMSYNC_DIR_NOT_FOUND ;;

		$E_BUILD_INMSYNC_FAILURE)
			echo "BUILD FAILURE FOR inmsync!"
			exit $E_BUILD_INMSYNC_FAILURE ;;

		$E_BUILD_SVFRD_FAILURE)
			echo "BUILD FAILURE FOR svfrd!"
			exit $E_BUILD_SVFRD_FAILURE ;;

		$E_BUILD_UNREG_FAILURE)
			echo "BUILD FAILURE FOR unregagent!"
			exit $E_BUILD_UNREG_FAILURE ;;

		$E_BUILD_ALERT_FAILURE)
			echo "BUILD FAILURE FOR alert!"
			exit $E_BUILD_ALERT_FAILURE ;;

		$E_BUILD_DSPACE_FAILURE)
			echo "BUILD FAILURE FOR dspace!"
			exit $E_BUILD_DSPACE_FAILURE ;;

		$E_BUILD_VACP_FAILURE)
			echo "BUILD FAILURE FOR vacp!"
			exit $E_BUILD_VACP_FAILURE ;;

		$E_VERSION_ARG_MISSING)
			echo "INCORRECT ARGUMENTS FOR fx_packaging.sh!"
			exit $E_VERSION_ARG_MISSING ;;

		$E_VERSION_BIN_DIR_NOT_FOUND)
			echo "DIRECTORY binaries/FX NOT FOUND UNDER ${TOP_BLD_DIR}!"
			exit $E_VERSION_BIN_DIR_NOT_FOUND ;;

		$E_VERSION_DCAL_NOT_FOUND)
			echo "FILE dcal NOT FOUND FOR THIS OS!"
			exit $E_VERSION_DCAL_NOT_FOUND ;;

		$E_PACKAGING_BINARIES_ABSENT)
			echo "ALL BINARIES REQUIRED FOR PACKAGING ARE NOT PRESENT!"
			exit $E_PACKAGING_BINARIES_ABSENT ;;

		$E_PACKAGING_PARTNER_DIR_ABSENT)
			echo "DIRECTORY $TOP_BLD_DIR/source/build/$PARTNER NOT FOUND!"
			exit $E_PACKAGING_PARTNER_DIR_ABSENT ;;

	esac
}

##
# Step 1: COMMAND LINE VALIDATION
# This would capture various parameters passed to this script, validates them and
# sets them to required variables
##

USAGE="CORRECT USAGE: $0 <valid CVS username> [-t <thirdparty path>] [top build dir] [partner] [valid CVS branch-name] [valid CVS tag name] [build-phase] [bld-quality] [Major Version] [Minor Version] [Release Number] [CONFIG]"

[ -z "$1" ] && echo $USAGE && exit 1

##
# Setting the variables
##

CVS_USERNAME=$1
if [ "$2" = "-t" ]; then
	THIRDPARTY_PATH=$3
	PARTNER=${5:-inmage}
	TOP_BLD_DIR=${4:-`pwd`}
	CVS_BRANCH=${6:-HEAD}
	CVS_TAG=${7:-HEAD}
	BUILDPHASE=${8:-DIT}
	BUILDQUALITY=${9:-DAILY}
	shift
	MAJOR_VERSION=${9:-6}
	shift
	MINOR_VERSION=${9:-50}
	shift
	REL_NUM=${9:-1}
	shift
	CONFIG=${9:-debug}
else
	PARTNER=${3:-inmage}
	TOP_BLD_DIR=${2:-`pwd`}
	CVS_BRANCH=${4:-HEAD}
	CVS_TAG=${5:-HEAD}
	BUILDPHASE=${6:-DIT}
	BUILDQUALITY=${7:-DAILY}
	MAJOR_VERSION=${8:-6}
	MINOR_VERSION=${9:-50}
	shift
	REL_NUM=${9:-1}
        shift
        CONFIG=${9:-debug}
fi

if [ -n "$THIRDPARTY_PATH" ]; then
    THIRDPARTY_ARG="-t $THIRDPARTY_PATH"
fi

CVS_CMD="cvs co -r $CVS_BRANCH"
SUFFIX=`date +%d`_`date +%b`_`date +%H`_`date +%M`_`date +%S`
FLOG="`pwd`/$TOP_BLD_DIR/logs/FX_Build_$SUFFIX.log"

[ "$PARTNER" = "both" ] && PARTNER="inmage xiotech"
Build_Dir=`echo $TOP_BLD_DIR | sed -e "s/\///g"`

if [ ! -f build_status_${Build_Dir} ]; then
        touch build_status_${Build_Dir}
        SETUP=1 CHECKOUT=1 BRANDING=1 VERSIONING=1 BUILD=1 PACKAGING=1
else
        if grep -iq "setup" build_status_${Build_Dir} ; then
                SETUP=0
        else
                SETUP=1
        fi

        if grep -iq "checkout" build_status_${Build_Dir} ; then
                CHECKOUT=0
        else
                CHECKOUT=1
        fi

        if grep -iq "branding_${PARTNER}" build_status_${Build_Dir} ; then
                BRANDING=0
        else
                BRANDING=1
        fi

        if grep -iq "versioning_${PARTNER}" build_status_${Build_Dir} ; then
                VERSIONING=0
        else
                VERSIONING=1
        fi

        if grep -iq "build_${PARTNER}" build_status_${Build_Dir} ; then
                BUILD=0
        else
                BUILD=1
        fi

        if grep -iq "packaging_${PARTNER}" build_status_${Build_Dir} ; then
                PACKAGING=0
        else
                PACKAGING=1
        fi
fi

##
# Step 2: BUILD ENVIRONMENT SETUP
# Making top dir for build
##

if [ $SETUP -eq 1 ]; then
    echo
    echo "Setting up required directory structure..."
    echo
    ./fx_bld_env_setup.sh $TOP_BLD_DIR $CVS_USERNAME
    SETUP_EXIT_STATUS=$?
    VERIFY $SETUP_EXIT_STATUS
    echo "setup" >> build_status_${Build_Dir}
else
    echo "Build directory structure setup already done for $TOP_BLD_DIR!"
fi

##
# Step 3: CHECKOUT
# Set variables and checkout files as required on the chosen OS
##

if [ $CHECKOUT -eq 1 ] ; then
    echo
    echo "Checking out source code now..."
    echo
    ./fx_checkout.sh $CVS_USERNAME $THIRDPARTY_ARG $TOP_BLD_DIR $CVS_TAG
    CHECKOUT_EXIT_STATUS=$?
    VERIFY $CHECKOUT_EXIT_STATUS
    echo "checkout" >> build_status_${Build_Dir}
else
    echo "Source code checkout already done for $TOP_BLD_DIR!"
fi

. ${TOP_BLD_DIR}/source/build/scripts/general/OS_details.sh

##
# Step 4: BRANDING
##

if [ $BRANDING -eq 1 ] ; then
        echo
        echo "Branding the source code and build environment variables now..."
        echo

        # Source the branding parameters script here. Working directory is source which contains the build folder
        . $TOP_BLD_DIR/source/build/branding/$PARTNER/branding_parameters.sh

        # Copy the branding_parameters.h file to host/branding
        cp $TOP_BLD_DIR/source/build/branding/$PARTNER/branding_parameters.h $TOP_BLD_DIR/source/host/branding

        echo "branding_${PARTNER}" >> build_status_${Build_Dir}
else
        echo "Source code and build environment branding already done for $TOP_BLD_DIR!"
fi

##
# Step 5: VERSIONING
# Create a version file which shall also be packaged along with the binaries
# Also update the build numbers, partner name etc, in the version.h file in <top-dir>/host/common
# This will help any future installs or upgrades
##

if [ $VERSIONING -eq 1 ] ; then
        echo
        echo "Changing version.h, generating .fx_version and .fx_build_manifest now..."
        echo

        ./fx_versioning.sh $TOP_BLD_DIR $PARTNER $CVS_BRANCH $BUILDQUALITY $BUILDPHASE $MAJOR_VERSION $MINOR_VERSION $REL_NUM
        VERSIONING_EXIT_STATUS=$?
        VERIFY $VERSIONING_EXIT_STATUS
        echo "versioning_${PARTNER}" >> build_status_${Build_Dir}
else
        echo "Generation of .fx_version and .fx_build_manifest, and change of version.h already done for $TOP_BLD_DIR!"
fi

case $OS in
   RHEL*|SLES*|OPENSUSE*|CITRIX*)
    if [ $BUILD -eq 1 ] ; then
        echo
        echo "Building and packaging the FX agent now..."
        echo
	cur_wd=`pwd`
	cd $TOP_BLD_DIR/source/host
	# If the version is 500 change the version in the spec files and in the build_params_partner.conf file
	sed -e "s/5.50.1/${MAJOR_VERSION}.${MINOR_VERSION}.${REL_NUM}/g" ../build/scripts/FX/build_params_${PARTNER}.conf >> ../build/scripts/FX/build_params_${PARTNER}.conf.new
	mv ../build/scripts/FX/build_params_${PARTNER}.conf.new ../build/scripts/FX/build_params_${PARTNER}.conf

	# Find the version from the spec file.
	version=`cat ../build/scripts/FX/templates/${PARTNER}.spec | grep "^Version" | cut -d":" -f2 | tr -d " "`
	release=`cat ../build/scripts/FX/templates/${PARTNER}.spec | grep "^Release" | cut -d":" -f2 | tr -d " "`
	sed -e "s/$version/${MAJOR_VERSION}.${MINOR_VERSION}/" ../build/scripts/FX/templates/${PARTNER}.spec >> ../build/scripts/FX/templates/${PARTNER}.spec.new
	mv ../build/scripts/FX/templates/${PARTNER}.spec.new ../build/scripts/FX/templates/${PARTNER}.spec

	sed -e "s/$release/${REL_NUM}/" ../build/scripts/FX/templates/${PARTNER}.spec >> ../build/scripts/FX/templates/${PARTNER}.spec.new
	mv ../build/scripts/FX/templates/${PARTNER}.spec.new ../build/scripts/FX/templates/${PARTNER}.spec

	make clean
	make X_VERSION_MAJOR=$MAJOR_VERSION X_VERSION_MINOR=$MINOR_VERSION X_VERSION_PHASE=$REL_NUM X_VERSION_QUALITY=$BUILDQUALITY X_VERSION_PHASE=$BUILDPHASE partner=$PARTNER debug=no verbose=yes fx_setup
	VERIFY $?
	cd ../../binaries/FX
	cp ../../source/host/`uname -ms | tr ' ' '_'`/setup/release/*.gz .
	VERIFY $?
	cd $cur_wd
	echo "build_${PARTNER}" >> build_status_${Build_Dir}
	echo "packaging_${PARTNER}" >> build_status_${Build_Dir}

        # Generating the symbols for FX

        if [ `uname` = "Linux" ]; then
                DATE_TIME_SUFFIX=`date +%d%b%Y`
                FX_VERSION=${MAJOR_VERSION}.${MINOR_VERSION}.${REL_NUM}

                for file in `find  $TOP_BLD_DIR/source/host -name "*.dbg"`
                do
                        BaseDir=`dirname $file`
                        BaseName=`basename $file`
                        tar --append --file=${COMPANY}_FX_${FX_VERSION}_${OS}_${BUILDPHASE}_${DATE_TIME_SUFFIX}_symbols.tar -C $BaseDir $BaseName
                done

                gzip ${COMPANY}_FX_${FX_VERSION}_${OS}_${BUILDPHASE}_${DATE_TIME_SUFFIX}_symbols.tar
                [ $? -eq 0 ] && echo "FX SYMBOL TAR FILE GENERATION IS SUCCESSFUL FOR $PARTNER on ${OS}..."

                mv ${COMPANY}_FX_${FX_VERSION}_${OS}_${BUILDPHASE}_${DATE_TIME_SUFFIX}_symbols.tar.gz $TOP_BLD_DIR/binaries/FX
                [ $? -eq 0 ] && echo "Copied symbol tar to $TOP_BLD_DIR/binaries/FX..."

        fi

    else
        echo "Build and Packaging already done for $TOP_BLD_DIR!"
    fi

	;;

*)

##
# Step 6: BUILD
# Default argument is 'all' (i.e. svfrd, unregagent). If you want
# selective build, pass comma-separated values
# e.g. ./build_common.sh svfrd,unregagent
##

if [ $BUILD -eq 1 ] ; then
    echo
    echo "Building the FX agent now..."
    echo
    ./fx_bld.sh $TOP_BLD_DIR all $CONFIG
    BUILD_EXIT_STATUS=$?
    VERIFY $BUILD_EXIT_STATUS
    echo "build_${PARTNER}" >> build_status_${Build_Dir}
else
    echo "Build already done for $TOP_BLD_DIR!"
fi

##
# Step 7: PACKAGING
# The packaging script replaces a lot of placeholder variables in the templates with some values at packaging time
# and leaves some others to be replaced at install time. It then copies all the required files into a temporary dir
# and creates an RPM or a TAR based on whether the operating system is Linux or otherwise.
##

if [ $PACKAGING -eq 1 ] ; then
    echo
    echo "Packaging the FX agent now..."
    echo
    ./fx_packaging.sh $PARTNER $TOP_BLD_DIR/binaries/FX $BUILDPHASE $CONFIG
    PACKAGING_EXIT_STATUS=$?
    VERIFY $PACKAGING_EXIT_STATUS
    echo "packaging_${PARTNER}" >> build_status_${Build_Dir}
else
    echo "Packaging already done for $TOP_BLD_DIR!"
fi
	;;
esac


#!/bin/sh -x

##
# Step 1: USAGE
# This would define the usage and also checks whether the build is successful
# or not for starting the packaging
##

# Define the usage
USAGE="Usage:   ./fx_packaging.sh [partner] [path of binaries]. Defaults are 'inmage' and current directory."

# Set the required variables from the parameters passed as arguments
PARTNER=${1:-inmage}
BINARY_PATH=${2:-`pwd`}
BUILD_PHASE=${3:-DIT}
CONFIG=${4:-debug}

DATE_TIME_SUFFIX=`date +%d%b%Y`

case $PARTNER in
		inmage)
				PARTNER_SPECIFIC_STRING="InMage";;
		xiotech)
				PARTNER_SPECIFIC_STRING="Xiotech";;
esac

# Check to see if build succeeded or not!
if [ -f $BINARY_PATH/svfrd ] && [ -f $BINARY_PATH/unregfragent ] && [ -f $BINARY_PATH/alert ] && [ -f $BINARY_PATH/dspace ] &&  [ -f $BINARY_PATH/remotecli ] && [ -f $BINARY_PATH/vacp ]
then
	echo "All required binaries ( svfrd, unregfragent, alert, dspace, remotecli and vacp ) are present. Starting the packaging process now..."
else
	echo "Since all or one of the required binaries ( svfrd,alert, dspace, unregfragent, remotecli and vacp) are not present, aborting packaging!"
	exit 105
fi

##
# Step 2:
# This would define the usage and also checks whether the build is successful
# or not for starting the packaging
##
# Now, if the control reached this point, it means that build was successful, so we can now go on with the packaging stuff
# Current directory is TOP_DIR/source
##

CUR_W_D=`pwd`

# Source the build parameters script here
. ./build_params_${PARTNER}.conf

cd $BINARY_PATH

# Guess the OS
. $BINARY_PATH/../../source/build/scripts/general/OS_details.sh

# Source the branding parameters script here
. ../../source/build/branding/$PARTNER/branding_parameters.sh

# Replace some placeholders in some of the template files during BUILD time
# Whatever placeholders remain will be replaced at INSTALL time

# 1. stop
sed -e "s|PARTNER_OR_COMPANY|$COMPANY|g" ../../source/build/scripts/FX/templates/stop > stop

# 2. start
sed -e "s|PARTNER_OR_COMPANY|$COMPANY|g" ../../source/build/scripts/FX/templates/start > start

# 3. status
sed -e "s|PARTNER_OR_COMPANY|$COMPANY|g" ../../source/build/scripts/FX/templates/status > status

# 4. uninstall
    sed -e "s|PARTNER_OR_COMPANY|$COMPANY|g" ../../source/build/scripts/FX/templates/uninstall | \
    sed -e "s|BUILDTIME_VALUE_RPM_PACKAGE|$BUILT_RPM_PACKAGE|" | \
    sed -e "s|BUILDTIME_VALUE_REF_DIR|$METADATA_REF_DIR|" | \
    sed -e "s|BUILDTIME_VALUE_BLD_MANIFEST_FILE_NAME|$BUILD_MANIFEST_FILE_NAME|" | \
    sed -e "s|BUILDTIME_VALUE_INST_VERSION_FILE|$VERSION_FILE_NAME|" > uninstall

# 5. unregister
sed -e "s|PARTNER_OR_COMPANY|$COMPANY|g" ../../source/build/scripts/FX/templates/unregister | \
sed -e "s|BUILDTIME_VALUE_REF_DIR|$METADATA_REF_DIR|" | \
sed -e "s|BUILDTIME_VALUE_INST_VERSION_FILE|$VERSION_FILE_NAME|" | \
sed -e "s|CX|$LABEL|g" > unregister

# 6. install
    sed -e "s|PARTNER_OR_COMPANY|$COMPANY|g" ../../source/build/scripts/FX/templates/install | \
    sed -e "s|CX|$LABEL|g" | sed -e "s|DEFAULT_PARTNER_INSTALL_DIR|$DEFAULT_INSTALL_DIR|g" | \
    sed -e "s|BUILDTIME_CURRENT_VERSION|$FX_VERSION|" | \
    sed -e "s|BUILDTIME_INST_VERSION_FILE|$VERSION_FILE_NAME|" | \
    sed -e "s|BUILDTIME_BUILD_MANIFEST_FILE|$BUILD_MANIFEST_FILE_NAME|" | \
    sed -e "s|BUILDTIME_MAIN_RPM_FILE|$BUILT_RPM_FILE|" | \
    sed -e "s|BUILDTIME_MAIN_RPM_PACKAGE|$BUILT_RPM_PACKAGE|" | \
    sed -e "s|BUILDTIME_DEFAULT_UPGRADE_DIR|$DEFAULT_UPG_DIR|" | \
    sed -e "s|BUILDTIME_PARTNER_SPECIFIC_STRING|$PARTNER_SPECIFIC_STRING|" | \
    sed -e "s|BUILDTIME_REF_DIR|$METADATA_REF_DIR|" > install

cp ../../source/build/scripts/FX/templates/svagent .
cp ../../source/build/scripts/FX/templates/config.ini .

# conf_file
sed -e "s|DEFAULT_PARTNER_INSTALL_DIR|$DEFAULT_INSTALL_DIR|g" ../../source/build/scripts/FX/templates/conf_file > conf_file

# Copy unchanged files from templates folder to the curr dir

cp ../../source/build/scripts/FX/templates/killchildren .
cp ../../source/host/vacp/ACM_SCRIPTS/linux/linuxshare_pre.sh .
cp ../../source/host/vacp/ACM_SCRIPTS/linux/linuxshare_post.sh .
cp ../../source/build/scripts/general/OS_details.sh .

# Get the OS variable
. ../../source/build/scripts/general/OS_details.sh

# Setting the option EnableDeleteOptions = 3255 instead of 0 so that it is enabled by default.

sed -e "s/EnableDeleteOptions = 0/EnableDeleteOptions = 3255/" config.ini > config.ini.new
mv config.ini.new config.ini
chmod +x config.ini

# Copy the fabric/oracle/fx scripts to curr dir
cp ../../source/Solutions/Fabric/Oracle/FX/*.sh .

# Copy the oracle/fx scripts to curr dir
cp ../../source/Solutions/Oracle/Fx/cx/logrm_applylist.sh .
cp ../../source/Solutions/Oracle/Fx/cx/logrm_mv_cx.sh .
cp ../../source/Solutions/Oracle/Fx/source/getDBsize.sh .
cp ../../source/Solutions/Oracle/Fx/source/prepdump.sh .
cp ../../source/Solutions/Oracle/Fx/target/preprestore.sh .
cp ../../source/Solutions/Oracle/Fx/target/recovermain.sh .
cp ../../source/Solutions/Oracle/Fx/target/recover.sh .

# Copy notices.txt here only if OS is not DEBIAN. For DEBIAN we are copying notices.txt in checkout step.
find $BINARY_PATH/../../source -name notices.txt -exec cp {} . \;

if [ -f $BINARY_PATH/notices.txt ]; then
    :
else
    echo "notices.txt file is missing ..."
    exit 1
fi

# Grant execute permissions to the scripts above
chmod -R 755 *.*

# This is specific to HPUX
# Giving the chatr enabled for all the binaries svfrd,unregfragent,alert,dspace,remotecli,vacp and inmsync
[ `uname` = "HP-UX" ] && chatr +s enable svfrd unregfragent alert dspace remotecli vacp inmsync

# Now, depending on the target operating system, differentiate the packaging procedure
# If it is RHEL4 or SuSE9 or SuSE10, use RPM. Otherwise, use a simple tar.gz and build the installing
# logic into the install script itself.

if [ `uname` = "SunOS" -a "$CONFIG" = "release" ]; then
	CONF="_release"
elif [ `uname` = "SunOS" -a "$CONFIG" = "debug" ]; then
	CONF="_debug"
else
	CONF=""
fi

# Create temporary directories for building the TAR
mkdir -p TAR_BUILD/lib TAR_BUILD/scripts TAR_BUILD/fabric/scripts
# Copy required files to this directory

		cp -f start stop status uninstall svagent svfrd inmsync unregister alert dspace \
		remotecli unregfragent vacp config.ini notices.txt killchildren TAR_BUILD/

		cp -f ../../source/lib/libgcc_s*  ../../source/lib/libstdc++* TAR_BUILD/lib/

		# Copy the oracle/fx scripts to TAR
		cp -f logrm_applylist.sh logrm_mv_cx.sh getDBsize.sh prepdump.sh preprestore.sh recovermain.sh recover.sh TAR_BUILD/scripts
		cp -f application.sh oracle.sh TAR_BUILD/fabric/scripts
		# Enter tar file name into version file as install script will use it
		echo "TAR_FILE_NAME=${COMPANY}_FX_${FX_VERSION}_${OS}.tar" >> $VERSION_FILE_NAME

		# Create the TAR now
		cd TAR_BUILD/
		tar -cvf ../${COMPANY}_FX_${FX_VERSION}_${OS}.tar .
		# If tar created successfully, create the final tar.gz
		if [ $? -eq 0 ]; then
			cd ..
			rm -rf TAR_BUILD/
			chmod +x install
			tar -cvf ${COMPANY}_FX_${FX_VERSION}_${OS}_${BUILD_PHASE}_${DATE_TIME_SUFFIX}${CONF}.tar \
			${COMPANY}_FX_${FX_VERSION}_${OS}.tar install OS_details.sh $VERSION_FILE_NAME \
			$BUILD_MANIFEST_FILE_NAME conf_file
			if [ $? -eq 0 ]; then
				gzip ${COMPANY}_FX_${FX_VERSION}_${OS}_${BUILD_PHASE}_${DATE_TIME_SUFFIX}${CONF}.tar
				[ $? -eq 0 ] && echo "FX BUILD AND PACKAGING IS SUCCESSFUL FOR $PARTNER on ${OS}..."
			fi
		fi

# Package the symbol files (.dbg) also

if [ `uname` = "SunOS" -a "$CONFIG" = "release" ]; then
    cd $BINARY_PATH
    tar -cvf ${COMPANY}_FX_${FX_VERSION}_${OS}_${BUILD_PHASE}_${DATE_TIME_SUFFIX}_${CONFIG}_symbols.tar *.dbg
    gzip ${COMPANY}_FX_${FX_VERSION}_${OS}_${BUILD_PHASE}_${DATE_TIME_SUFFIX}_${CONFIG}_symbols.tar
    [ $? -eq 0 ] && echo "FX SYMBOL TAR FILE GENERATION IS SUCCESSFUL FOR $PARTNER on ${OS}..."
fi

# Change directories back to the original working directory at the start of this script
cd $CUR_W_D


#!/bin/sh -x

USAGE="Usage:   ./fx_versioning.sh <top build dir> [partner] [branch] [buildquality] [buildphase] [Major Version] [Minor Version] [Release Number]. Default value for arguments in square brackets are 'inmage', 'HEAD', 'DAILY' and 'DIT'."
[ -z "$1" ] && echo $USAGE && exit 85

##
# Setting the required variables
##

TOP_BLD_DIR=$1
PARTNER=${2:-inmage}
branchName=${3:-HEAD}
buildQuality=${4:-DAILY}
buildPhase=${5:-DIT}
verYear=`date +%Y`
verMonth=`date +%h`
verDate=`date +%d`
maj_ver=${6:-5}
min_ver=${7:-50}

patch_set_ver=00
patch_ver=00

rel_num=${8:-1}
bld_seq_num=1
relTagString="${buildQuality}_${maj_ver}-${min_ver}-${rel_num}_${buildPhase}"

case $branchName in
        TRUNK|TRUNC|HEAD|SCOUT_7-2_OSS_SEC_FIXES_BRANCH)
                refSecs=1104517800 ;;
esac

PATCH_VERSION=${maj_ver}.${min_ver}.${patch_set_ver}.${patch_ver}

##
# Calculate the number of seconds elapsed till now from UNIX epoch
# and thereby the tag name for this particular release
# There are 2 ways of calculating this figure - either by date +%s
# command or by compiling and storing in CVS a program called dcal
# which can return the figure. date +%s seems to be more like
# a GNU extension than anything else so don't expect all OSes to
# accommodate this command-argument.
##

. ${TOP_BLD_DIR}/source/build/scripts/general/OS_details.sh
DCAL_BIN="${TOP_BLD_DIR}/source/build/scripts/general/bin/dcal_${OS}"

if [ -f $DCAL_BIN ]; then
	no_of_secs_now=`$DCAL_BIN`
else
        no_of_secs_now=`date +%s`
fi

dlybldNum=`expr \`expr $no_of_secs_now - $refSecs\` / 86400`

case $PARTNER in
        inmage|InMage) PARTNER_VERSION_STRING="InMage" ;;
        xiotech|Xiotech) PARTNER_VERSION_STRING="Xiotech" ;;
        *) echo "$partner not handled yet in this script...aborting!" && exit 1 ;;
esac

tagName="${relTagString}_${dlybldNum}_${verMonth}_${verDate}_${verYear}_${PARTNER_VERSION_STRING}"

##################################
# Source the build param file here
# All env variables used to hold
# constants for this build are to
# be found in that file...
# This is an attempt to minimise
# any sort of hardcoding........
##################################

# Change the version depending on the version that is passed as an argument
# If the version is 500 change the version in the spec files and in the build_params_partner.conf file
sed -e "s/6.50.00.00/${maj_ver}.${min_ver}.00.00/g" build_params_${PARTNER}.conf >> build_params_${PARTNER}.conf.new
mv build_params_${PARTNER}.conf.new build_params_${PARTNER}.conf

# Find the version from the spec file.
version=`cat templates/${PARTNER}.spec | grep "^Version" | cut -d":" -f2 | tr -d " "`
release=`cat templates/${PARTNER}.spec | grep "^Release" | cut -d":" -f2 | tr -d " "`
sed -e "s/$version/${maj_ver}.${min_ver}/" templates/${PARTNER}.spec >> templates/${PARTNER}.spec.new
mv templates/${PARTNER}.spec.new templates/${PARTNER}.spec

sed -e "s/$release/${rel_num}/" templates/${PARTNER}.spec >> templates/${PARTNER}.spec.new
mv templates/${PARTNER}.spec.new templates/${PARTNER}.spec

. ./build_params_${PARTNER}.conf

##################################
# Create the version file here
##################################

if [ -d $TOP_BLD_DIR/binaries/FX ]; then
  echo "VERSION=$FX_VERSION" > $TOP_BLD_DIR/binaries/FX/${VERSION_FILE_NAME}
  echo "PROD_VERSION=$PATCH_VERSION" >> $TOP_BLD_DIR/binaries/FX/${VERSION_FILE_NAME}
  echo "PARTNER=$PARTNER" >> $TOP_BLD_DIR/binaries/FX/${VERSION_FILE_NAME}
  echo "INSTALLATION_DIR=RUNTIME_INSTALL_PATH" >> $TOP_BLD_DIR/binaries/FX/${VERSION_FILE_NAME}
  if [ `uname` = "Linux" ] && [ ! -e /etc/debian_version ] ; then
  	echo "RPM_PACKAGE=$BUILT_RPM_PACKAGE" >> $TOP_BLD_DIR/binaries/FX/${VERSION_FILE_NAME}
  	echo "RPM_NAME=$BUILT_RPM_FILE" >> $TOP_BLD_DIR/binaries/FX/${VERSION_FILE_NAME}
  fi
  echo "VERSION_FILE_PARENT_DIR=$METADATA_REF_DIR" >> $TOP_BLD_DIR/binaries/FX/${VERSION_FILE_NAME}
  echo "DEFAULT_UPGRADE_DIR=$DEFAULT_UPG_DIR" >> $TOP_BLD_DIR/binaries/FX/${VERSION_FILE_NAME}
  echo "BUILD_TAG=$tagName" >> $TOP_BLD_DIR/binaries/FX/${VERSION_FILE_NAME}
  echo "OS_BUILT_FOR=$OS" >> $TOP_BLD_DIR/binaries/FX/${VERSION_FILE_NAME}

else
  exit 87
fi

######################################
# Create the build manifest file here
######################################

if [ -d $TOP_BLD_DIR/binaries/FX ]; then
  # 2. List of files
  # Since CVS/Entries contains entries for files checked out, it's easy to copy its contents to this file without much ado
  echo >> $TOP_BLD_DIR/binaries/FX/${BUILD_MANIFEST_FILE_NAME}
  echo >> $TOP_BLD_DIR/binaries/FX/${BUILD_MANIFEST_FILE_NAME}
  echo "Following is the list of files used in this build:" >> $TOP_BLD_DIR/binaries/FX/${BUILD_MANIFEST_FILE_NAME}
  echo >> $TOP_BLD_DIR/binaries/FX/${BUILD_MANIFEST_FILE_NAME}
  echo >> $TOP_BLD_DIR/binaries/FX/${BUILD_MANIFEST_FILE_NAME}
  find $TOP_BLD_DIR/source -type f -name "Entries" -exec cat {} \; | grep -v CVS | grep -v "^D" \
	>> $TOP_BLD_DIR/binaries/FX/${BUILD_MANIFEST_FILE_NAME}
else
  exit 87
fi

######################################################################################
# Version file should be changed to reflect correct release versions and partner names
######################################################################################

if [ -f $TOP_BLD_DIR/source/host/fr_common/version.h ]; then
	sed -n "s/INMAGE_PRODUCT_VERSION_STR[ ]\{1,\}\".*\"/INMAGE_PRODUCT_VERSION_STR \"$tagName\"/p" \
		$TOP_BLD_DIR/source/host/fr_common/version.h > $TOP_BLD_DIR/source/host/fr_common/version.h.new
	sed -n "s/INMAGE_PRODUCT_VERSION[ ]\{1,\}[0-9,]*/INMAGE_PRODUCT_VERSION $maj_ver,${min_ver}${rel_num},\
${dlybldNum},${bld_seq_num}/p" $TOP_BLD_DIR/source/host/fr_common/version.h \
			>> $TOP_BLD_DIR/source/host/fr_common/version.h.new
	sed -n "s/INMAGE_PRODUCT_VERSION_MAJOR[ ]\{1,\}[0-9]*/INMAGE_PRODUCT_VERSION_MAJOR $maj_ver/p" \
		$TOP_BLD_DIR/source/host/fr_common/version.h >> $TOP_BLD_DIR/source/host/fr_common/version.h.new
	sed -n "s/INMAGE_PRODUCT_VERSION_MINOR[ ]\{1,\}[0-9]*/INMAGE_PRODUCT_VERSION_MINOR ${min_ver}${rel_num}/p" \
		$TOP_BLD_DIR/source/host/fr_common/version.h >> $TOP_BLD_DIR/source/host/fr_common/version.h.new
	sed -n "s/INMAGE_PRODUCT_VERSION_BUILDNUM[ ]\{1,\}[0-9]*/INMAGE_PRODUCT_VERSION_BUILDNUM $dlybldNum/p" \
		$TOP_BLD_DIR/source/host/fr_common/version.h >> $TOP_BLD_DIR/source/host/fr_common/version.h.new
	sed -n "s/INMAGE_PRODUCT_VERSION_PRIVATE[ ]\{1,\}[0-9]*/INMAGE_PRODUCT_VERSION_PRIVATE $bld_seq_num/p" \
		$TOP_BLD_DIR/source/host/fr_common/version.h >> $TOP_BLD_DIR/source/host/fr_common/version.h.new
	sed -n "s/INMAGE_HOST_AGENT_CONFIG_CAPTION[ ]\{1,\}\".*\"/INMAGE_HOST_AGENT_CONFIG_CAPTION \"$tagName\"/p" \
		$TOP_BLD_DIR/source/host/fr_common/version.h >> $TOP_BLD_DIR/source/host/fr_common/version.h.new
	sed -n "s/PROD_VERSION[ ]\{1,\}\".*\"/PROD_VERSION \"$PATCH_VERSION\"/p" \
		$TOP_BLD_DIR/source/host/fr_common/version.h >> $TOP_BLD_DIR/source/host/fr_common/version.h.new

       	mv $TOP_BLD_DIR/source/host/fr_common/version.h.new $TOP_BLD_DIR/source/host/fr_common/version.h
fi

######################################################################################
# End of correcting version file
######################################################################################


#! /bin/sh

if [ `uname` = 'SunOS' ]; then
        # Export LD_LIBRARY_PATH
	LD_LIBRARY_PATH=RUNTIME_INSTALL_PATH/Pillar/lib
        export LD_LIBRARY_PATH
fi

RUNTIME_INSTALL_PATH/Pillar/bin1/`basename $0` "$@"


#! /bin/sh

if [ `uname` = 'SunOS' ]; then
        # Export LD_LIBRARY_PATH
        LD_LIBRARY_PATH=RUNTIME_INSTALL_PATH/lib64:
        export LD_LIBRARY_PATH
fi

if [ `uname` = 'AIX' ]; then
        # Export LIBPATH
        LIBPATH=SET_LIBPATH
        export LIBPATH
fi

/usr/local/InMage/Fx/bin1/`basename $0` "$@"


#! /bin/sh

echo "--------------------------------------------"
echo `date`

# Check whether installation directory is mounted or not. If it is not mounted wait for 60 secs.
# Repeat the loop for 30 times and exit if installation directory is not mounted even after 30 mins.
# If installation directory is mounted within 30 mins then invoke soft_removal.sh.
i="1"
while [ $i -lt 31 ]
do
        echo "Iteration : $i"
        if [ -f RUNTIME_INSTALL_PATH/start ]; then
                echo "RUNTIME_INSTALL_PATH/start is available"
                sleep 15
                echo "Inovking RUNTIME_INSTALL_PATH/start"
                RUNTIME_INSTALL_PATH/start
                break
        else
                if [ "$i" = "30" ]; then
                        echo "Installation directory is not mounted even after 30 minutes. Existing..."
                        exit
                fi
                echo "Installation directory is not mounted. sleeping for 60 secs"
                sleep 60
        fi
        i=`expr $i + 1`
done


#!/bin/bash
#####################################################################################
#Purpose: Used to apply custom configuration changes on CentOS/RHEL 6.6 Master Target
######################################################################################

DO()
{
    eval "$1 2>> $LOG_FILE | tee -a $LOG_FILE"
}

DATE_TIME_SUFFIX=`date +%d_%b_%Y_%H:%M:%S`
LOG_FILE=/var/log/appliedmtcustomchanges.log

echo -e "\t$DATE_TIME_SUFFIX" >> $LOG_FILE
echo -e "\t####################\n" >> $LOG_FILE

if [ -e /etc/.appliedmtcustomchanges ]; then
    DO 'echo'
    DO 'echo "--------------------------------------------------------------------------------"'
    DO 'echo "ApplyCustomChanges.sh script was already invoked. Please re-try the installation"'
    DO 'echo "--------------------------------------------------------------------------------"'
    exit 0
fi

DO 'echo -e "\tCustom Configuration\n"'
DO 'echo -e "\t####################\n"'

DO 'echo "WARNING: This script is intended to be executed only on Master Target servers. "'
DO 'echo "         If this server is not a Master Target, please do not continue. "'
DO 'echo'
while [ "X$Choice" = "X" ]
do
    DO 'echo -n "Are you sure you want to continue? [Y|N] [default N] : "'
    read Choice
    if [ -z "$Choice" -o "$Choice" = "N" -o "$Choice" = "n" ]; then
        Choice="N" ; exit 1
    elif [ "$Choice" = "Y" -o "$Choice" = "y" ];then
        Choice="Y"
    else
        Choice=""
        DO 'echo -e "Invalid answer. Please retry.\n"'
    fi
done

# Make sure only root can run our script
DO 'echo -n "Checking for root privileges ... "'
[[ $EUID -ne 0 ]] && DO 'echo "FAILED"' && DO 'echo "This script must be run as root"' && exit 1
DO 'echo "OK"'

# Make sure OS is RedHat/CentOS 6.6(64bit)
DO 'echo -n "Checking for Ubuntu 16.04(64bit) or Ubuntu 20.04(64bit) ... "'
if egrep -q 'DISTRIB_RELEASE=16.04|DISTRIB_RELEASE=20.04' /etc/lsb-release ; then
	if uname -a | grep -q x86_64; then
		OSCheck=0
	else
        OSCheck=1
    fi
else
    OSCheck=1
fi

if [ $OSCheck -ne 0 ]; then
   DO 'echo "FAILED"' && exit 1
else
   DO 'echo "OK"'
fi

# Make sure required packages are available.
DO 'echo -n "Checking for required software packages ... "'
REQ_PKG_LIST="apt multipath-tools lsscsi kpartx python-pyasn1 lvm2"
if grep -q 'DISTRIB_RELEASE=16.04' /etc/lsb-release ; then
    REQ_PKG_LIST="$REQ_PKG_LIST linux-image-generic-hwe-16.04"
fi

rm -f /var/log/missing-packages.log /dev/null 2>&1
for pkgName in `echo $REQ_PKG_LIST`
do
    if dpkg -l |grep $pkgName > /dev/null 2>&1 ; then
       PKG_MISSING=0
    else
        PKG_MISSING=1
        echo "package $pkgName is not installed." >>/var/log/missing-packages.log
    fi
done
[[ $PKG_MISSING -ne 0 ]] && DO 'echo "FAILED"' || DO 'echo "OK"'
if [ -s /var/log/missing-packages.log ]; then
    DO 'echo'
    DO 'cat /var/log/missing-packages.log'
	DO 'echo "Command to install package: apt-get install package-name"'
    DO 'echo "Please install missing packages and re-try. Aborting..."'
    exit 1
fi

# Set core file size to unlimited
DO 'echo -n "Set core file size to unlimited ... "'
sed -i -e '/ulimit -c unlimited/d' /etc/bash.bashrc
echo "ulimit -c unlimited" >> /etc/bash.bashrc
[[ $? -ne 0 ]] && DO 'echo "FAILED"'|| DO 'echo "OK"'

# multipath.conf file creation
DO 'echo -n "Creating multipath.conf file ... "'
cat > /etc/multipath.conf << EOF
defaults {
        user_friendly_names no
		find_multipaths no
}

blacklist {
#For AT Lun masking
        device {
                vendor  "InMage"
        }
devnode "^cciss!c[0-9]d[0-9]*"
}
EOF
[[ $? -ne 0 ]] && DO 'echo "FAILED"'|| DO 'echo "OK"'

# Creating default multipath.conf file
DO 'echo -n "Configuring multipath to blacklist cciss disk ... "'
sed -i -e '/^blacklist[[:space:]]*{/ a devnode "^cciss!c[0-9]d[0-9]*"' /etc/multipath.conf
[[ $? -ne 0 ]] && DO 'echo "FAILED"' || DO 'echo "OK"'

# Black listing root device and enabled multipath
DO 'echo -n "Blacklist root disk and enable multipath... "'
BootDevice=`mount | grep "on / " | awk '{print $1}'`
BootDevice=`echo ${BootDevice} | sed -e "s:[sp]*[0-9]*$::"`
WWID=`/lib/udev/scsi_id --whitelisted --device=$BootDevice`
cat > /usr/sbin/blacklistrootdev.sh << EOF
[[ -n "$WWID" ]] && sed -i -e "/^blacklist.*{/ a wwid $WWID" /etc/multipath.conf || exit 1
if [ -f /.blacklistrootdev ] ; then
    sed -i "/^wwid/d" /etc/multipath.conf ; sed -i -e "/^blacklist.*{/ a wwid $WWID" /etc/multipath.conf
fi
EOF
chmod 755 /usr/sbin/blacklistrootdev.sh
[[ -f /etc/multipath.conf ]] && /usr/sbin/blacklistrootdev.sh > /var/log/blacklistrootdev.log 2>&1
touch /.blacklistrootdev > /dev/null 2>&1
[[ $? -ne 0 ]] && DO 'echo "FAILED"' || DO 'echo "OK"'

# Creating dummy file to restrict multiple execution
touch /etc/.appliedmtcustomchanges >/dev/null 2>&1

DO 'echo -e "*** NOTE: REBOOT IS REQUIRED FOR CUSTOM CHANGES TO TAKE EFFECT.***\n"'
DO 'echo -e "\n\t********** COMPLETED ************"'
DO 'echo -e "\t##################################\n"'


#!/bin/sh

BRANCHES="INT_BRANCH REL_BRANCH INTERIM_REL_BRANCH"
TODAY_DAY=`date +%b_%d_%Y`

# Tag host modules for all applicable branches
echo > ./host_status

for BRANCH_NAME in $BRANCHES
do
	MODULES="admin build host server Solutions"
	case $BRANCH_NAME in
        INT_BRANCH)
                BRANCH_CODE=INT_BRANCH
                QUALITY=DAILY
                PHASE=DIT
                ;;
        REL_BRANCH)
                BRANCH_CODE=REL_BRANCH
                QUALITY=RELEASE
                PHASE=GA
                ;;
        INTERIM_REL_BRANCH)
                BRANCH_CODE=INTERIM_REL_BRANCH
                QUALITY=RELEASE
                PHASE=GA
                ;;
	esac

	# Export the source CVSROOT
	export CVSROOT=:pserver:vegogine@10.150.24.11:/src
	TODAY_TAG=${QUALITY}_${BRANCH_CODE}_${PHASE}_${TODAY_DAY}
	echo "$BRANCH_NAME Today's Tag		: ${TODAY_TAG}"

	echo "Cmd: cvs rtag -F -r ${BRANCH_NAME} ${TODAY_TAG} ${MODULES}"
	cvs rtag -F -r ${BRANCH_NAME} ${TODAY_TAG} ${MODULES}
	if [ $? -eq 0 ]; then
		echo "Applied ${TODAY_TAG} successfully! ..."
                echo "Source Tagging     : ${BRANCH_NAME} - ${TODAY_TAG} - Successful" >> ./host_status
	else
		echo "Could not apply ${TODAY_TAG}. Tagging failed..."
		echo "Source Tagging     : ${BRANCH_NAME} - ${TODAY_TAG} - Failed" >> ./host_status
	fi
	echo
	echo

	echo >> ./host_status
	echo
	echo
done

grep -q "Failed" ./host_status
if [ $? -eq 0 ]; then
	RESULT="FAILED"
else
	RESULT="SUCCESSFUL"
fi

# Send mail to inmiet@microsoft.com about the host tagging status
mail -s "SOURCE TAGGING : ${RESULT}" inmiet@microsoft.com <<DATA
`cat -v ./host_status`
DATA

# Tag thirdparty modules for all applicable branches
echo > ./tp_status

BRANCHES="INT_BRANCH REL_BRANCH INTERIM_REL_BRANCH"
TODAY_DAY=`date +%b_%d_%Y`

for BRANCH_NAME in $BRANCHES
do
        case $BRANCH_NAME in
        INT_BRANCH)
                BRANCH_CODE=INT_BRANCH
                QUALITY=DAILY
                PHASE=DIT
                ;;
        REL_BRANCH)
                BRANCH_CODE=REL_BRANCH
                QUALITY=RELEASE
                PHASE=GA
                ;;
        INTERIM_REL_BRANCH)
                BRANCH_CODE=INTERIM_REL_BRANCH
                QUALITY=RELEASE
                PHASE=GA
                ;;
        esac

        # Export the Thirpdarty CVSROOT
        export CVSROOT=:pserver:vegogine@10.150.24.11:/thirdparty

	TODAY_TAG=${QUALITY}_${BRANCH_CODE}_${PHASE}_${TODAY_DAY}
	echo "$BRANCH_NAME Today's Tag		: ${TODAY_TAG}"

        echo "Cmd: cvs rtag -F -r ${BRANCH_NAME} ${TODAY_TAG} thirdparty"
        cvs rtag -F -r ${BRANCH_NAME} ${TODAY_TAG} thirdparty
        if [ $? -eq 0 ]; then
                echo "Applied ${TODAY_TAG} successfully! ..."
                echo "Thirdparty Tagging : ${BRANCH_NAME} - ${TODAY_TAG} - Successful" >> ./tp_status
        else
                echo "Could not apply ${TODAY_TAG}. Tagging failed..."
                echo "Thirdparty Tagging : ${BRANCH_NAME} - ${TODAY_TAG} - Failed" >> ./tp_status
        fi
	echo >> ./tp_status
        echo
        echo
done

grep -q "Failed" ./tp_status
if [ $? -eq 0 ]; then
        RESULT="FAILED"
else
        RESULT="SUCCESSFUL"
fi

# Send mail to inmiet@microsoft.com about the thirdparty status
mail -s "THIRDPARTY TAGGING : ${RESULT}" inmiet@microsoft.com <<DATA
`cat -v ./tp_status`
DATA


#!/bin/sh

if [ -f /etc/oracle-release ]; then
    if grep -q 'Oracle Linux Server release 6.*' /etc/oracle-release; then
        VERSION=`sed "s/[^0-9]*//g" /etc/oracle-release`
	    if [ `uname -m` = "x86_64" -a $VERSION -ge 64 ]; then
            OS="OL6-64"
        fi
    elif grep -q 'Oracle Linux Server release 7.*' /etc/oracle-release; then
        if [ `uname -m` = "x86_64" ]; then
            OS="OL7-64"
        fi
    elif grep -q 'Oracle Linux Server release 8.*' /etc/oracle-release; then
        if [ `uname -m` = "x86_64" ]; then
            OS="OL8-64"
        fi
    fi
elif [ -f /etc/redhat-release ]; then
    if grep -q 'Red Hat Enterprise Linux Server release 5.*' /etc/redhat-release || \
        grep -q 'CentOS release 5.*' /etc/redhat-release; then
	VERSION=`sed "s/[^0-9]*//g" /etc/redhat-release`
	if [ `uname -m` = "x86_64" -a $VERSION -ge 52 -a $VERSION -le 511 ]; then
            OS="RHEL5-64"
        fi
    elif grep -q 'Red Hat Enterprise Linux Server release 6.*' /etc/redhat-release || \
        grep -q 'Red Hat Enterprise Linux Workstation release 6.*' /etc/redhat-release || \
        grep -q 'CentOS Linux release 6.*' /etc/redhat-release ||
        grep -q 'CentOS release 6.*' /etc/redhat-release; then
	if [ `uname -m` = "x86_64" ]; then
            OS="RHEL6-64"
        fi
    elif grep -q 'Red Hat Enterprise Linux Server release 7.*' /etc/redhat-release || \
        grep -q 'Red Hat Enterprise Linux Workstation release 7.*' /etc/redhat-release || \
        grep -q 'CentOS Linux release 7.*' /etc/redhat-release; then
	if [ `uname -m` = "x86_64" ]; then
            OS="RHEL7-64"
        fi
    elif grep -q 'Red Hat Enterprise Linux release 8.*' /etc/redhat-release || \
        grep -q 'CentOS Linux release 8.*' /etc/redhat-release; then
	if [ `uname -m` = "x86_64" ]; then
            OS="RHEL8-64"
        fi
    fi
elif [ -f /etc/SuSE-release ]; then
    if grep -q 'VERSION = 11' /etc/SuSE-release && grep -q 'PATCHLEVEL = 3' /etc/SuSE-release; then
	if [ `uname -m` = "x86_64" ]; then
            OS="SLES11-SP3-64"
        fi
    elif grep -q 'VERSION = 11' /etc/SuSE-release && grep -q 'PATCHLEVEL = 4' /etc/SuSE-release; then
	if [ `uname -m` = "x86_64" ]; then
            OS="SLES11-SP4-64"
        fi
    fi
    if grep -q 'VERSION = 12' /etc/SuSE-release; then
        if [ `uname -m` = "x86_64" ]; then
            OS="SLES12-64"
        fi
    elif grep -q 'VERSION="15' /etc/SuSE-release; then
        if [ `uname -m` = "x86_64" ]; then
            OS="SLES15-64"
        fi
    fi
elif [ -f /etc/os-release ] && grep -q 'SLES' /etc/os-release; then
    if grep -q 'VERSION="15' /etc/os-release; then
        if [ `uname -m` = "x86_64" ]; then
            OS="SLES15-64"
        fi
    fi
elif [ -f /etc/lsb-release ] ; then
    if grep -q 'DISTRIB_RELEASE=14.04' /etc/lsb-release ; then
	if [ `uname -m` = "x86_64" ]; then
            OS="UBUNTU-14.04-64"
        fi
    elif grep -q 'DISTRIB_RELEASE=16.04' /etc/lsb-release ; then
	if [ `uname -m` = "x86_64" ]; then
            OS="UBUNTU-16.04-64"
        fi
    elif grep -q 'DISTRIB_RELEASE=18.04' /etc/lsb-release ; then
	if [ `uname -m` = "x86_64" ]; then
            OS="UBUNTU-18.04-64"
        fi
    elif grep -q 'DISTRIB_RELEASE=20.04' /etc/lsb-release ; then
	if [ `uname -m` = "x86_64" ]; then
            OS="UBUNTU-20.04-64"
        fi
    fi
elif [ -f /etc/debian_version ]; then
    if grep -q '^7.*' /etc/debian_version; then
        if [ `uname -m` = "x86_64" ]; then
            OS="DEBIAN7-64"
        fi
    elif grep -q '^8.*' /etc/debian_version; then
        if [ `uname -m` = "x86_64" ]; then
            OS="DEBIAN8-64"
        fi
    elif grep -q '^9.*' /etc/debian_version; then
        if [ `uname -m` = "x86_64" ]; then
            OS="DEBIAN9-64"
        fi
    elif grep -q '^10.*' /etc/debian_version; then
        if [ `uname -m` = "x86_64" ]; then
            OS="DEBIAN10-64"
        fi
    fi
fi

if [ $# -gt 0 ]
then
    echo $OS
fi


##################
# DEFAULT VALUES
##################

DATE=`date '+%d%h%Y'`
CALLING_SCRIPT="$1"
MAIL_ID="dl-build-engineering@inmage.net"
WRK_DIR=`pwd`

##############
# VALIDATIONS
##############

GDB=`which gdb`

if [ -z "$CALLING_SCRIPT" ] || [ -z "$OS" ] || [ -z "$GDB" ]; then
	echo
        echo "Either all the arguments are not defined or GDB is not installed in the setup ..."
	echo "Cannot proceed with the symbol checking ..."
	echo
        exit 1
fi

###########################
# Start the sendmail
###########################

case $OS in
	SLES*|OPENSUSE*)
		PS=`pgrep -f /usr/lib/postfix/master`
		if [ -z "$PS" ] ; then
			/etc/init.d/postfix start
		fi
	;;
	*)
		PS=`pgrep sendmail`
		if [ -z "$PS" ] ; then
			/etc/init.d/sendmail start
		fi
	;;
esac

#################################
# Find the machine Architecture
#################################

case `uname -m` in
        i586|i686)
                ARCH=Linux_i686
        ;;
         x86_64)
                ARCH=Linux_x86_64
	;;
esac

########################
# Cleaning the gdb log
########################

Clean_Up()
{
  BUILD_TYPE=$1

  if [ -f ${BIN_DIR}/GDB_${BUILD_TYPE}_${OS}.log ]; then
  	rm -f ${BIN_DIR}/GDB_${BUILD_TYPE}_${OS}.log
  fi
}

###############################
# Check if the symbol tar or
# the build exists or not
###############################

Pre_Check()
{
  if [ -z "$SYMBOL_TAR_FILE" ] || [ -z "$BUILD_TAR_FILE" ]; then
	echo
	echo "Either the symbol file or the build tar is missing ..."
	echo "Cannot proceed with the symbol verification . Aborting ..."
	exit 1
  fi
}

########################################
# Execute the GDB here
# Check if the gdb is matching
# with the corresponding binary or not
########################################

FUNC_GDB_TEST()
{
  BINARY_FILE=$1
  GDB_FILE=$2
  BUILD_TYPE=$3
  NO_SYMS_FOUND=""
  if [ `uname -s` = "SunOS" ] ;then
	GREP='/usr/xpg4/bin/grep'
  else
	GREP=`which grep`
  fi

  gdb ${BINARY_FILE} --symbols=${GDB_FILE} >gdb.log<<DATA
q
DATA

  if $GREP -q 'no debugging symbols found' gdb.log  ; then
  	NO_SYMS_FOUND="$NO_SYMS_FOUND $file"
  fi

  echo "gdb ${BINARY_FILE} --symbols=${GDB_FILE}" >>${BIN_DIR}/GDB_${BUILD_TYPE}_${OS}.log
  cat gdb.log >>${BIN_DIR}/GDB_${BUILD_TYPE}_${OS}.log
  echo >>${BIN_DIR}/GDB_${BUILD_TYPE}_${OS}.log

  if [ -n "$NO_SYMS_FOUND" ] ; then
  	mail -s "SYMBOL VERIFICATION : Symbol Verification on $OS for ${BINARY_FILE} --- FAILED" $MAIL_ID <<EOF
EOF
  fi
}

###############################
# Verifying the symbols for FX
###############################

FUNC_SYM_FX()
{
  BUILD_TYPE=FX

  Clean_Up $BUILD_TYPE

  if [ "${OS}" = "RHEL6-64" ]; then
      OS="RHEL6U2-64"
  fi

  SYMBOL_TAR_FILE=`ls -1 $BIN_DIR/InMage_UA_${MAJOR_VERSION}.${MINOR_VERSION}*${OS}*symbols.tar.gz`

  BUILD_TAR_FILE=`ls -1 $BIN_DIR/InMage_FX_${MAJOR_VERSION}.${MINOR_VERSION}*release.tar.gz`

  Pre_Check

  tar --wildcards -xzvf ${BUILD_TAR_FILE} "InMageFx-*"
  FX_TAR_NAME=`ls -1 InMageFx-*`

  rpm2cpio "$FX_TAR_NAME" | cpio -ivd
  cd $SYM_DIR/InMage/Fx

  tar -xzvf ${SYMBOL_TAR_FILE}
  CUR_DIR=`pwd`

  for symfile in `find . -name "*.dbg"`
  do
	DBG_DIR=`dirname $symfile`
	cd $DBG_DIR
	binfile=`basename $symfile`
	binfile=`ls $binfile | awk -F'.' '{ print $1 }'`

        cp $SYM_DIR/InMage/Fx/$binfile .
        FUNC_GDB_TEST $binfile ${binfile}.dbg $BUILD_TYPE
        cd $CUR_DIR
  done
}

##########################################
# Check for Solaris VX Symbols
# This includes Pushinstall client also
##########################################

FUNC_SYM_VX()
{
  BUILD_TYPE=VX

  Clean_Up $BUILD_TYPE

  SYMBOL_TAR_FILE=`ls -1 $BIN_DIR/InMage_VX_*symbols.tar.gz`

  BUILD_TAR_FILE=`ls -1 $BIN_DIR/InMage_VX_*release.tar.gz`

  Pre_Check

  cp $SYMBOL_TAR_FILE $BUILD_TAR_FILE .
  gunzip *.tar.gz

  SYMBOL_TAR_FILE=`ls -1 InMage_VX_*${OS}*symbols.tar`
  BUILD_TAR_FILE=`ls -1 InMage_VX_*release.tar`

  mkdir -p $SYM_DIR/InMage/Vx
  cd $SYM_DIR/InMage/Vx

  tar -xvf  ${SYM_DIR}/$BUILD_TAR_FILE
  tar -xvf  InMage_VX_*.tar bin1
  cd bin1

  tar -xvf ${SYM_DIR}/${SYMBOL_TAR_FILE}
  CUR_DIR=`pwd`

  for symfile in `find $CUR_DIR -name "*.dbg"`
   do
	DBG_DIR=`dirname $symfile`
	binfile=`basename $symfile`
	binfile=`ls $binfile | awk -F'.' '{ print $1 }'`
	cd $DBG_DIR

	if [ "$binfile" = "pushinstallclient" ]; then
		cp /BUILDS/SCRIPTS/head_daily_builds/release/pushinstallclient .
		FUNC_GDB_TEST $binfile ${binfile}.dbg $BUILD_TYPE
		cd $CUR_DIR
		continue
	fi

	cp $SYM_DIR/InMage/Vx/bin1/$binfile .
	FUNC_GDB_TEST $binfile ${binfile}.dbg $BUILD_TYPE
	cd $CUR_DIR
	continue
  done
}

##########################################
# Check for Solaris FX Symbols only
##########################################

FUNC_Unix_SYM_FX()
{
  BUILD_TYPE=FX

  Clean_Up $BUILD_TYPE

  SYMBOL_TAR_FILE=`ls -1 $BIN_DIR/InMage_FX_*symbols.tar.gz`

  BUILD_TAR_FILE=`ls -1 $BIN_DIR/InMage_FX_*release.tar.gz`

  Pre_Check

  cp $SYMBOL_TAR_FILE $BUILD_TAR_FILE .
  gunzip *.tar.gz

  SYMBOL_TAR_FILE=`ls -1 InMage_FX_*${OS}*symbols.tar`
  BUILD_TAR_FILE=`ls -1 InMage_FX_*release.tar`

  mkdir -p $SYM_DIR/InMage/Fx
  cd $SYM_DIR/InMage/Fx

  tar -xvf  ${SYM_DIR}/$BUILD_TAR_FILE
  tar -xvf  InMage_FX_*.tar

  tar -xvf ${SYM_DIR}/${SYMBOL_TAR_FILE}
  CUR_DIR=`pwd`

  for symfile in `find $CUR_DIR -name "*.dbg"`
   do
        DBG_DIR=`dirname $symfile`
        binfile=`basename $symfile`
        binfile=`ls $binfile | awk -F'.' '{ print $1 }'`
        cd $DBG_DIR

        cp $SYM_DIR/InMage/Fx/$binfile .
        FUNC_GDB_TEST $binfile ${binfile}.dbg $BUILD_TYPE
        cd $CUR_DIR
        continue
  done
}

##########################################
# Do not keep quotes in DEBIAN or UBUNTU
# While extracting the FX or VX tars
##########################################

FUNC_SYM_UA()
{
  BUILD_TYPE=UA

  Clean_Up $BUILD_TYPE

  SYMBOL_TAR_FILE=`ls -1 $BIN_DIR/InMage_UA_${MAJOR_VERSION}.${MINOR_VERSION}*${OS}*symbols.tar.gz`

  BUILD_TAR_FILE=`ls -1 $BIN_DIR/InMage_UA_${MAJOR_VERSION}.${MINOR_VERSION}*release.tar.gz`

  Pre_Check

  case $OS in
        DEBIAN*|UBUNTU*)
                mkdir -p InMage/Fx InMage/Vx

                cd $SYM_DIR/InMage/Fx

                tar --wildcards -xzvf $BUILD_TAR_FILE "InMage_FX_*.tar"
                tar --wildcards -xvf InMage_FX_*.tar

                cd $SYM_DIR/InMage/Vx

                tar --wildcards -xzvf $BUILD_TAR_FILE "InMage_VX_*.tar"
                tar --wildcards -xvf InMage_VX_*.tar

                tar -xzvf ${SYMBOL_TAR_FILE}
                LIST=`find -name *.dbg | egrep  '(storagefailover|unlockVolumes|sendquit|pushinstalld)'`

                rm $LIST

        ;;
              *)
                tar --wildcards -xzvf ${BUILD_TAR_FILE} 'InMageVx-*'

                VX_TAR_NAME=`ls -1 InMageVx-*`
                rpm2cpio "$VX_TAR_NAME" | cpio -ivd

                tar --wildcards -xzvf ${BUILD_TAR_FILE} 'InMageFx-*'

                FX_TAR_NAME=`ls -1 InMageFx-*`
                rpm2cpio "$FX_TAR_NAME" | cpio -ivd

                cd $SYM_DIR/InMage/Vx/bin

                tar -xzvf ${SYMBOL_TAR_FILE}
        ;;
  esac
  CUR_DIR=`pwd`

  for symfile in `find . -name *.dbg`
  do
        DBG_DIR=`dirname $symfile`
        cd $DBG_DIR
        binfile=`ls | awk -F'.' '{ print $1 }'`

	if [ "$binfile" = "pushinstallclient" ]; then
		cd $CUR_DIR
		continue
	fi

	if [ "$binfile" = "fabricagent" ] ; then
	 	case $OS in
	  		RHEL5U1-64)
				cp $SYM_DIR/InMage/Vx/bin/$binfile .
				FUNC_GDB_TEST $binfile ${binfile}.dbg $BUILD_TYPE
                		cd $CUR_DIR
                		continue
	   		;;
			*)
				cd $CUR_DIR
                		continue
	 	esac
	fi

	if [ -f $SYM_DIR/InMage/Vx/bin/$binfile ] ; then
	        cp $SYM_DIR/InMage/Vx/bin/$binfile .
	elif [ -f $SYM_DIR/InMage/Fx/$binfile ] ; then
		cp $SYM_DIR/InMage/Fx/$binfile .
	elif [ -f $SYM_DIR/InMage/Fx/transport/$binfile ] ; then
		cp $SYM_DIR/InMage/Fx/transport/$binfile .
	else
	 	mail -s "The corresponding binary $binfile is not found for $OS." $MAIL_ID <<EOF
EOF
	fi

	FUNC_GDB_TEST $binfile ${binfile}.dbg $BUILD_TYPE
	cd $CUR_DIR
done
}

###############################
# Verifying the symbols for CX
###############################

FUNC_SYM_CX()
{
  BUILD_TYPE=CX

  Clean_Up $BUILD_TYPE

  if [ "${OS}" = "RHEL6-64" ]; then
      OS="RHEL6U2-64"
  fi

  SYMBOL_TAR_FILE=`ls -1tr $BIN_DIR/SYMBOLS/InMage_Scout_CX_${MAJOR_VERSION}.${MINOR_VERSION}*${OS}_*_${verDate}${verMonth}${verYear}_release_symbol.tar.gz`

  BUILD_TAR_FILE=`ls -1tr $BIN_DIR/InMage_Scout_CX_${MAJOR_VERSION}.${MINOR_VERSION}*_${OS}_*_${verDate}${verMonth}${verYear}.tar.gz`

  Pre_Check

  tar --wildcards -xzvf ${BUILD_TAR_FILE} Scout-CX-*/inmage*.rpm Scout-CX-*/pushinstalld Scout-CX-*/storagefailover
  cd Scout-CX-*
  tar -xzvf ${SYMBOL_TAR_FILE}

  rpm2cpio inmagePS-* | cpio -ivd ./home/svsystems/bin/bwm ./home/svsystems/bin/diffdatasort ./home/svsystems/bin/inmtouch ./home/svsystems/bin/svdcheck
  rpm2cpio inmageCS-* | cpio -ivd ./home/svsystems/bin/inmlicense ./home/svsystems/bin/scheduler

  mv ./home/svsystems/bin/bwm ./home/svsystems/bin/diffdatasort ./home/svsystems/bin/inmtouch  ./home/svsystems/bin/svdcheck ./home/svsystems/bin/inmlicense ./home/svsystems/bin/scheduler .

  for symfile in `ls -1 *.dbg`
  do
 	binfile=`ls $symfile | awk -F'.' '{ print $1 }'`
	mkdir ${binfile}_dir
	mv $binfile ${binfile}.dbg ${binfile}_dir
	cd ${binfile}_dir
        FUNC_GDB_TEST $binfile ${binfile}.dbg $BUILD_TYPE
	cd -
  done
}

################################################
# Verifying the symbols for Push Install Client
# This will not be verified as part of the UA
################################################

FUNC_SYM_PUSH()
{
  BUILD_TYPE=PUSH

  Clean_Up $BUILD_TYPE

  SYMBOL_TAR_FILE=`ls -1 $BIN_DIR/SYMBOLS/InMage_pushinstallclient_${MAJOR_VERSION}.${MINOR_VERSION}*${OS}_*release_symbol.tar.gz`

  BUILD_TAR_FILE=`ls -1 $BIN_DIR/${OS}_pushinstallclient.tar.gz`

  Pre_Check

  tar -xzvf $BUILD_TAR_FILE
  tar -xzvf $SYMBOL_TAR_FILE

  for symfile in `ls -1 *.dbg`
  do
        binfile=`ls $symfile | awk -F'.' '{ print $1 }'`
        FUNC_GDB_TEST $binfile ${binfile}.dbg $BUILD_TYPE
  done
}

###################
# MAIN ENTRY POINT
###################

##################################
# Find the Calling script and
# Execute the gdb test accordingly
#################################

case "$CALLING_SCRIPT" in

	*UA*.sh)

		case $OS in
                        SLES9-32|SLES9-64|RHEL3-32)
                                BIN_DIR=/BUILDS/$BRANCH/BINARIES/UNIFIED

				if [ -d "$BIN_DIR/SYM_CHK" ] ; then
                                        rm -rf "$BIN_DIR/SYM_CHK"
                                fi

				mkdir -p $BIN_DIR/SYM_CHK
                                cd $BIN_DIR/SYM_CHK
                                SYM_DIR=`pwd`
                                FUNC_SYM_FX

				#Clean up for Linux FX builds after use
				if [ -d "$BIN_DIR/SYM_CHK" ] ; then
					cd $WRK_DIR
					rm -rf "$BIN_DIR/SYM_CHK"
				fi

                                BIN_DIR="/BUILDS/$BRANCH/BINARIES/PUSH"

                                if [ -d "$BIN_DIR/SYM_CHK" ] ; then
                                                 rm -rf "$BIN_DIR/SYM_CHK"
                                fi

                                mkdir -p $BIN_DIR/SYM_CHK
                                cd $BIN_DIR/SYM_CHK
                                FUNC_SYM_PUSH

				#Clean up for Linux push builds after use
				if [ -d "$BIN_DIR/SYM_CHK" ] ; then
					cd $WRK_DIR
					rm -rf "$BIN_DIR/SYM_CHK"
				fi

			;;
			*Solaris*)
				# For VX and Push
				BIN_DIR="/BUILDS/$BRANCH/BINARIES/UNIFIED"

				if [ -d "$BIN_DIR/SYM_CHK" ] ; then
					rm -rf "$BIN_DIR/SYM_CHK"
				fi
				mkdir -p $BIN_DIR/SYM_CHK

				cd $BIN_DIR/SYM_CHK
				SYM_DIR=`pwd`
				FUNC_Unix_SYM_FX
				cd $BIN_DIR/SYM_CHK
				FUNC_SYM_VX
				#Clean up for Solaris platforms after use
				if [ -d "$BIN_DIR/SYM_CHK" ] ; then
					cd $WRK_DIR
                                	rm -rf "$BIN_DIR/SYM_CHK"
				fi
			;;
			*)
				BIN_DIR="/BUILDS/$BRANCH/BINARIES/UNIFIED"

				if [ -d "$BIN_DIR/SYM_CHK" ] ; then
					rm -rf "$BIN_DIR/SYM_CHK"
				fi

				mkdir -p $BIN_DIR/SYM_CHK
				cd $BIN_DIR/SYM_CHK
				SYM_DIR=`pwd`
                                FUNC_SYM_UA

				#Clean up for Linux UA builds after us
				if [ -d "$BIN_DIR/SYM_CHK" ] ; then
					cd $WRK_DIR
					rm -rf "$BIN_DIR/SYM_CHK"
				fi

				BIN_DIR="/BUILDS/$BRANCH/BINARIES/PUSH"

                                if [ -d "$BIN_DIR/SYM_CHK" ] ; then
					 cd $WRK_DIR
                                         rm -rf "$BIN_DIR/SYM_CHK"
                                fi

                                mkdir -p $BIN_DIR/SYM_CHK
                                cd $BIN_DIR/SYM_CHK
				FUNC_SYM_PUSH

				#Clean up for Linux push builds after use
				if [ -d "$BIN_DIR/SYM_CHK" ] ; then
					cd $WRK_DIR
					rm -rf "$BIN_DIR/SYM_CHK"
				fi

                esac
	;;
	*CX*.sh)
		if [ -d "$BIN_DIR/SYM_CHK" ] ; then
                        rm -rf "$BIN_DIR/SYM_CHK"
                fi

		mkdir -p $BIN_DIR/SYM_CHK
		cd $BIN_DIR/SYM_CHK
		FUNC_SYM_CX

		#Clean up for Linux CX builds after use
		if [ -d "$BIN_DIR/SYM_CHK" ] ; then
			cd $WRK_DIR
			rm -rf "$BIN_DIR/SYM_CHK"
		fi
	;;

	*)
		echo
		echo "Either the build type is unknown or there is no symbol support for this type of build"
		echo
		exit 1
	;;
esac


####################
# DEFAULT VARIABLES
####################

TOP_BLD_DIR=${1:?"Enter the path to the TOP BUILD directory!"}
PARTNER=${2:-inmage}
GIT_BRANCH=${3:-develop}
GIT_TAG=${4:-develop}
BUILD_QUALITY=${5:-RELEASE}
BUILD_PHASE=${6:-GA}
MAJOR_VERSION=${7:-9}
MINOR_VERSION=${8:-50}
PATCH_SET_VERSION=${9:-0}
shift
PATCH_VERSION=${9:-0}
shift
AGENT_TYPE=${9:-both}
shift
CONFIGURATION=${9:-both}
shift
FTP_BUILD=${9:-no}
shift
TIER_NUMBER=${9:-tier1}

BINARIES_PATH_FOR_UA=/BUILDS/${GIT_BRANCH}/BINARIES/UNIFIED

X_ARCH=`uname -ms | sed "s/ /_/g"`

if [ "$FTP_BUILD" = "yes" ]; then
    FTP_PATH="/DailyBuilds/Daily_Builds/${MAJOR_VERSION}.${MINOR_VERSION}"
fi

CWD=`pwd`
MAIL_ID="inmiet@microsoft.com"
date_suffix=`date +%e_%b_%Y | awk '{print $1}'`
SCP_SERVER="10.150.24.13"

Before_Build_Tasks()
{
	if [ ! -d ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source ]; then
		rm -rf ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build
		mkdir -p ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source
	fi

	cd ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/

	# Update repo if it exists already, otherwise clone it.
	if [ -d InMage-Azure-SiteRecovery ]; then
                echo "InMage-Azure-SiteRecovery repo already exists."
		cd InMage-Azure-SiteRecovery
        	# Checkout code from appropriate branch, update code and remove any local files.
	        git checkout ${GIT_BRANCH} && git fetch origin && git reset --hard origin/${GIT_BRANCH} && git clean -xdf
       		if [ $? -eq 0 ]; then
			echo "Successfully checked out code from ${GIT_BRANCH} and removed local files."
        	else
			echo "Failed to check out code from ${GIT_BRANCH} and remove local files."
                	exit 1
        	fi
	else
                echo "InMage-Azure-SiteRecovery repo does not exist."
		git clone -b ${GIT_BRANCH} --single-branch msazure@vs-ssh.visualstudio.com:v3/msazure/One/InMage-Azure-SiteRecovery
        	if [ $? -eq 0 ]; then
                	echo "Successfully cloned InMage-Azure-SiteRecovery git repo and branch ${GIT_BRANCH}."
                	cd InMage-Azure-SiteRecovery
        	else
                	echo "Failed to clone InMage-Azure-SiteRecovery git repo and branch ${GIT_BRANCH}."
                	exit 1
        	fi
	fi

	. ./build/scripts/general/OS_details.sh

	if [ "$CONFIGURATION" = "both" ]; then
		CONFIGURATION='release debug'
	fi

	chmod -R +x build/scripts/unifiedagent
	cd build/scripts/unifiedagent

	CLEAN_REPO="no"
	./checkout.sh ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build $GIT_TAG $CLEAN_REPO
	if [ $? -ne 0 ]; then
		echo "Failed to setup InMage-Azure-SiteRecovery git repo."
		exit 1
	fi

	Build_Dir=`echo ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build | sed -e "s/\///g"`

	if [ -e build_status_${Build_Dir} ]; then
		rm -f build_status_${Build_Dir}
	fi
	touch build_status_${Build_Dir}
	echo "checkout" >> build_status_${Build_Dir}

	mkdir -p ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/
}

# Package Azure Recovery Utils
Package_AzureRecoveryTools()
{
    case $OS in
        UBUNTU-16.04-64)
            if [ "${CONFIGURATION}" = "release" ]; then
                CUR_DIR=`pwd`

                rm -rf ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools

                if [ ! -d ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools ] || [ ! -d ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools/SYMBOLS ]; then
                    mkdir -p ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools/SYMBOLS
                fi

                if  [ -e ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/host/${X_ARCH}/AzureRecoveryUtil/release/AzureRecoveryUtil ]; then
                    mv ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/host/${X_ARCH}/AzureRecoveryUtil/release/AzureRecoveryUtil ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools
                    cp ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/host/AzureRecoveryUtil/Scripts/linux/{*.sh,network,CentOS-Base.repo} ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools
					cp ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/thirdparty/setuptools-31.1.1/{*.py,*.zip} ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools
                    mv ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/host/${X_ARCH}/AzureRecoveryUtil/release/AzureRecoveryUtil.dbg ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools/SYMBOLS

                    cd ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools/SYMBOLS
                    tar cvfz InMage_AzureRecoveryUtil_${MAJOR_VERSION}.${MINOR_VERSION}.${PATCH_SET_VERSION}.${PATCH_VERSION}_${OS}_${BUILD_PHASE}_`date +%d``date +%b``date +%Y`_release_symbol.tar.gz AzureRecoveryUtil.dbg
                    cd ${CUR_DIR}
               else
                    echo "AzureRecoveryUtil binary is not available."
                    cd ${CUR_DIR}
                    return 1
               fi
          fi
     ;;
     esac
}

Package_Push_Client()
{
    if [ "${CONFIGURATION}" = "release" ]; then
        CUR_DIR=`pwd`

        rm -rf ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/PUSH

        if [ ! -d ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/PUSH ] || [ ! -d ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/PUSH/SYMBOLS ]; then
            mkdir -p ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/PUSH ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/PUSH/SYMBOLS
        fi

        if [ -e ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/host/${X_ARCH}/pushInstallerCli/release/pushinstallclient ]; then
            mv ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/host/${X_ARCH}/pushInstallerCli/release/pushinstallclient ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/PUSH
            mv ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/host/${X_ARCH}/pushInstallerCli/release/pushinstallclient.dbg ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/PUSH/SYMBOLS

            cd ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/PUSH
            tar cvfz ${OS}_pushinstallclient.tar.gz pushinstallclient
            cp ${OS}_pushinstallclient.tar.gz ${OS}_pushinstallclient_${MAJOR_VERSION}.${MINOR_VERSION}.tar.gz
            cd ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/PUSH/SYMBOLS
            tar cvfz InMage_pushinstallclient_${MAJOR_VERSION}.${MINOR_VERSION}.${PATCH_SET_VERSION}.${PATCH_VERSION}_${OS}_${BUILD_PHASE}_`date +%d``date +%b``date +%Y`_release_symbol.tar.gz pushinstallclient.dbg
            cd ${CUR_DIR}
        fi
    fi
}

UA_Build()
{
    for CONFIGURATION in $CONFIGURATION
    do
        sh -x ./makefile_complete.sh -d ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build -T /BUILDS/${GIT_BRANCH}/SOURCE/thirdparty -b ${GIT_BRANCH} -B ${GIT_TAG} -p ${PARTNER} -c ${CONFIGURATION} -q ${BUILD_QUALITY} -P ${BUILD_PHASE} -M ${MAJOR_VERSION} -N ${MINOR_VERSION} -S ${PATCH_SET_VERSION} -V ${PATCH_VERSION} -A ${AGENT_TYPE} inmbuild > ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/UA_${OS}_${CONFIGURATION}.log 2>&1

        if [ "${CONFIGURATION}" = "release" ]; then
            Package_Push_Client
            Package_AzureRecoveryTools
            After_Build_Tasks
            Symbol_Check
            if [ "$FTP_BUILD" = "yes" ]; then
                Scp_Release
            fi
        fi

        if [ "${CONFIGURATION}" = "debug" ]; then
            After_Build_Tasks
            if [ "$FTP_BUILD" = "yes" ]; then
                Scp_Debug
            fi
        fi
    done
}

#######################################################
# FUNCTION : After_Build_Tasks
# Copy the required binaries to
# BINARIES path ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES
#######################################################

After_Build_Tasks()
{
    mv ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/binaries/*.tar.gz ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/
    mv ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/binaries/FX/*.tar.gz ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/
    mv ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/binaries/VX/*.tar.gz ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/

    ls -1 ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/*UA*.tar.gz
    if [ $? -ne 0 ]; then
        HOSTNAME=`hostname`
        mail -s "UA BUILD FAILURE ON $OS WITH HOSTNAME $HOSTNAME FOR ${GIT_BRANCH} FOR ${CONFIGURATION} CONFIGURATION . PLEASE CHECK THE LOGS FOR COMPLETE RESULTS" $MAIL_ID <<DATA
DATA
    fi

    rm -f ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/binaries/*.gz
    rm -f ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/binaries/FX/*
    rm -f ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/binaries/VX/*
    rm -f ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/logs/FX/*
    rm -f ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/logs/VX/*

    # Generate OS specific agent version file.
    AGENT_VERSION=`grep -w INMAGE_PRODUCT_VERSION ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/host/common/version.h | tr ',' '.' | cut -d" " -f3 | tr -d "\n"`
    echo -n ${AGENT_VERSION} > ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/AgentVersion_${AGENT_VERSION}_${OS}.txt

    # Copy supported_kernels file if it has some content.
    if [ -s ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/host/drivers/InVolFlt/linux/supported_kernels ] ; then
        cp -f ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/host/drivers/InVolFlt/linux/supported_kernels /BUILDS/${GIT_TAG}/BINARIES/UNIFIED/${OS}_supported_kernels.txt
    elif [ -s ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/host/drivers/InVolFlt/linux/sles_drivers/supported_kernels ] ; then
        cp -f ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/host/drivers/InVolFlt/linux/sles_drivers/supported_kernels /BUILDS/${GIT_TAG}/BINARIES/UNIFIED/${OS}_supported_kernels.txt
    fi

    # Copy AgentVersion.txt and copy OS_details.sh which will be used by A2A extenstion. Also, copy supported_kernels file.
    if [ "$OS" = "SLES12-64" ]; then
        echo -n ${AGENT_VERSION} > ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/AgentVersion.txt
        cp -f ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/build/scripts/general/OS_details.sh ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/
        cp -f ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/host/drivers/InVolFlt/linux/sles_drivers/supported_kernels /BUILDS/${GIT_TAG}/BINARIES/UNIFIED/${OS}_supported_kernels.txt
    fi

}

#############################################
# FUNCTIONS : Scp_Release Scp_Debug
# Used for copying the UA builds to 10.150.24.13
#############################################
Scp_Debug()
{
    # debug builds are not used in ASR
    return 0
}

MakeDir_Remote()
{
    remotedirpath=$1
    # retry the remote command for 5 mins
    starttime=`date +%s`
    while :
    do
        ssh $SCP_SERVER "mkdir -p $remotedirpath"
        if [ $? -eq 0 ]; then
            break
        fi

        currtime=`date +%s`
        elapsed=`expr $currtime - $starttime`
        if [ $elapsed -gt 300 ]; then
            echo "Retries of mkdir failed"
            return 1
        fi

        sleep 5
        echo "retrying mkdir command"
    done
}

Copy_To_Remote()
{
    localfilespath=$1
    remotedirpath=$2

    for localfilepath in `ls $localfilespath`
    do
        # retry the remote command for 5 mins
        starttime=`date +%s`
        while :
        do
            scp $localfilepath $SCP_SERVER:$remotedirpath
            if [ $? -eq 0 ]; then
                break
            fi

            currtime=`date +%s`
            elapsed=`expr $currtime - $starttime`
            if [ $elapsed -gt 300 ]; then
                echo "Retries of scp failed"
                return 1
            fi

            sleep 5
            echo "retrying scp command"
        done
    done
}

Scp_Release()
{
    DATE_FOLDER=`date +%d_%b_%Y | awk '{print $1}'`

    MakeDir_Remote "${FTP_PATH}/HOST/${DATE_FOLDER}/UnifiedAgent_Builds/release/symbol_tars"
    MakeDir_Remote "${FTP_PATH}/HOST/${DATE_FOLDER}/UnifiedAgent_Builds/release/logs"
    MakeDir_Remote "${FTP_PATH}/HOST/${DATE_FOLDER}/UnifiedAgent_Builds/release/supported_kernels"
    MakeDir_Remote "${FTP_PATH}/HOST/${DATE_FOLDER}/UnifiedAgent_Builds/release/agent_versions"
    MakeDir_Remote "${FTP_PATH}/HOST/${DATE_FOLDER}/PushInstallClients/symbol_tars"
    MakeDir_Remote "${FTP_PATH}/HOST/${DATE_FOLDER}/PushInstallClientsRcm"
    MakeDir_Remote "${FTP_PATH}/HOST/${DATE_FOLDER}/release/AzureRecoveryTools/Symbols"

    Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/*UA*release.tar.gz ${FTP_PATH}/HOST/${DATE_FOLDER}/UnifiedAgent_Builds/release/
    Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/*UA*release_symbols.tar.gz ${FTP_PATH}/HOST/${DATE_FOLDER}/UnifiedAgent_Builds/release/symbol_tars/

    Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/OS_details.sh ${FTP_PATH}/HOST/${DATE_FOLDER}/UnifiedAgent_Builds/release/
    Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/AgentVersion.txt ${FTP_PATH}/HOST/${DATE_FOLDER}/UnifiedAgent_Builds/release/

    #Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/GDB*.log ${FTP_PATH}/HOST/${DATE_FOLDER}/UnifiedAgent_Builds/release/logs/
    Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/UA*release.log ${FTP_PATH}/HOST/${DATE_FOLDER}/UnifiedAgent_Builds/release/logs/
    Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/AgentVersion_*.txt ${FTP_PATH}/HOST/${DATE_FOLDER}/UnifiedAgent_Builds/release/agent_versions/
    Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/*supported_kernels.txt ${FTP_PATH}/HOST/${DATE_FOLDER}/UnifiedAgent_Builds/release/supported_kernels/

    Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/PUSH/*pushinstallclient.tar.gz ${FTP_PATH}/HOST/${DATE_FOLDER}/PushInstallClients/
    Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/PUSH/SYMBOLS/*.tar.gz ${FTP_PATH}/HOST/${DATE_FOLDER}/PushInstallClients/symbol_tars/
    Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/PUSH/*pushinstallclient_${MAJOR_VERSION}.${MINOR_VERSION}.tar.gz ${FTP_PATH}/HOST/${DATE_FOLDER}/PushInstallClientsRcm/

    if [ "$OS" = "UBUNTU-16.04-64" ]; then
        Copy_To_Remote "${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools/*.sh" ${FTP_PATH}/HOST/${DATE_FOLDER}/release/AzureRecoveryTools/
        Copy_To_Remote "${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools/*.py" ${FTP_PATH}/HOST/${DATE_FOLDER}/release/AzureRecoveryTools/
        Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools/CentOS-Base.repo ${FTP_PATH}/HOST/${DATE_FOLDER}/release/AzureRecoveryTools/
        Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools/network ${FTP_PATH}/HOST/${DATE_FOLDER}/release/AzureRecoveryTools/
        Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools/AzureRecoveryUtil ${FTP_PATH}/HOST/${DATE_FOLDER}/release/AzureRecoveryTools/
        Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools/SYMBOLS/*.tar.gz  ${FTP_PATH}/HOST/${DATE_FOLDER}/release/AzureRecoveryTools/Symbols/
    fi

    Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/UA_WRAPPER_log  ${FTP_PATH}/HOST/${DATE_FOLDER}/UnifiedAgent_Builds/release/logs/UA_${OS}_WRAPPER.log
}

#####################################
# FUNCTION : Symbol_Check
# Executing the Symbol check for all
# the linux platforms
#####################################

Symbol_Check()
{
  cd $CWD
  # cvs co -r $GIT_TAG build/scripts/general/SYMBOL_CHECK.sh
  export TOP_BLD_DIR PARTNER GIT_BRANCH GIT_TAG BUILD_QUALITY BUILD_PHASE MAJOR_VERSION MINOR_VERSION AGENT_TYPE OS
  BRANCH=$GIT_TAG
  export BRANCH
  if [ -d InMage-Azure-SiteRecovery ]; then
      sh -x InMage-Azure-SiteRecovery/build/scripts/general/SYMBOL_CHECK.sh "$0"
  else
      sh -x build/scripts/general/SYMBOL_CHECK.sh "$0"
  fi
}

#####################
# MAIN ENTRY POINT
#####################

rm -f ${BINARIES_PATH_FOR_UA}/*.tar.gz ${BINARIES_PATH_FOR_UA}/*.log ${BINARIES_PATH_FOR_UA}/*.txt

Before_Build_Tasks

UA_Build


#!/bin/sh

if [ -f /etc/oracle-release ]; then
    if grep -q 'Oracle Linux Server release 6.*' /etc/oracle-release; then
        if [ `uname -m` = "x86_64" ]; then
            OS="OL6-64: `cat /etc/oracle-release`: 0"
        fi
    elif grep -q 'Oracle Linux Server release 7.*' /etc/oracle-release; then
        if [ `uname -m` = "x86_64" ]; then
            OS="OL7-64: `cat /etc/oracle-release`: 0"
        fi
    elif grep -q 'Oracle Linux Server release 8.*' /etc/oracle-release; then
        if [ `uname -m` = "x86_64" ]; then
            OS="OL8-64: `cat /etc/oracle-release`: 0"
        fi
    fi

    if [ -z "$OS" ]; then
        OS="Unsupported: `cat /etc/oracle-release` `uname -m`: 1"
    fi
elif [ -f /etc/redhat-release ]; then
    if grep -q 'Red Hat Enterprise Linux Server release 5.*' /etc/redhat-release || \
        grep -q 'CentOS release 5.*' /etc/redhat-release; then
        VERSION=`sed "s/[^0-9]*//g" /etc/redhat-release`
        if [ `uname -m` = "x86_64" -a $VERSION -ge 52 -a $VERSION -le 511 ]; then
            OS="RHEL5-64: `cat /etc/redhat-release`: 0"
        fi
    elif grep -q 'Red Hat Enterprise Linux Server release 6.*' /etc/redhat-release || \
        grep -q 'Red Hat Enterprise Linux Workstation release 6.*' /etc/redhat-release || \
        grep -q 'CentOS Linux release 6.*' /etc/redhat-release ||
        grep -q 'CentOS release 6.*' /etc/redhat-release; then
        if [ `uname -m` = "x86_64" ]; then
            OS="RHEL6-64: `cat /etc/redhat-release`: 0"
        fi
    elif grep -q 'Red Hat Enterprise Linux Server release 7.*' /etc/redhat-release || \
        grep -q 'Red Hat Enterprise Linux Workstation release 7.*' /etc/redhat-release || \
        grep -q 'CentOS Linux release 7.*' /etc/redhat-release; then
        if [ `uname -m` = "x86_64" ]; then
            OS="RHEL7-64: `cat /etc/redhat-release`: 0"
        fi
    elif grep -q 'Red Hat Enterprise Linux release 8.*' /etc/redhat-release || \
        grep -q 'CentOS Linux release 8.*' /etc/redhat-release; then
        if [ `uname -m` = "x86_64" ]; then
            OS="RHEL8-64: `cat /etc/redhat-release`: 0"
        fi
    fi

    if [ -z "$OS" ]; then
        OS="Unsupported: `cat /etc/redhat-release` `uname -m`: 1"
    fi
elif [ -f /etc/SuSE-release ]; then
    if grep -q 'VERSION = 11' /etc/SuSE-release && grep -q 'PATCHLEVEL = 3' /etc/SuSE-release; then
        if [ `uname -m` = "x86_64" ]; then
            OS="SLES11-SP3-64: `cat /etc/SuSE-release`: 0"
        fi
    elif grep -q 'VERSION = 11' /etc/SuSE-release && grep -q 'PATCHLEVEL = 4' /etc/SuSE-release; then
        if [ `uname -m` = "x86_64" ]; then
            OS="SLES11-SP4-64: `cat /etc/SuSE-release`: 0"
        fi
    fi
    if grep -q 'VERSION = 12' /etc/SuSE-release; then
        if [ `uname -m` = "x86_64" ]; then
            OS="SLES12-64: `cat /etc/SuSE-release`: 0"
        fi
    elif grep -q 'VERSION="15' /etc/SuSE-release; then
        if [ `uname -m` = "x86_64" ]; then
            OS="SLES15-64: `cat /etc/SuSE-release | grep PRETTY | cut -d '"' -f 2`: 0"
        fi
    fi

    if [ -z "$OS" ]; then
        OS="Unsupported: `cat /etc/SuSE-release` `uname -m`: 1"
    fi
elif [ -f /etc/os-release ] && grep -q 'SLES' /etc/os-release; then
    if grep -q 'VERSION="15' /etc/os-release; then
        if [ `uname -m` = "x86_64" ]; then
            OS="SLES15-64: `cat /etc/os-release | grep PRETTY | cut -d '"' -f 2`: 0"
        fi
    fi

    if [ -z "$OS" ]; then
        OS="Unsupported: `cat /etc/os-release` `uname -m`: 1"
    fi
elif [ -f /etc/lsb-release ] ; then
    if grep -q 'DISTRIB_RELEASE=14.04' /etc/lsb-release ; then
        if [ `uname -m` = "x86_64" ]; then
            OS="UBUNTU-14.04-64: `cat /etc/lsb-release`: 0"
        fi
    elif grep -q 'DISTRIB_RELEASE=16.04' /etc/lsb-release ; then
        if [ `uname -m` = "x86_64" ]; then
            OS="UBUNTU-16.04-64: `cat /etc/lsb-release`: 0"
        fi
    elif grep -q 'DISTRIB_RELEASE=18.04' /etc/lsb-release ; then
        if [ `uname -m` = "x86_64" ]; then
            OS="UBUNTU-18.04-64: `cat /etc/lsb-release`: 0"
        fi
    elif grep -q 'DISTRIB_RELEASE=20.04' /etc/lsb-release ; then
        if [ `uname -m` = "x86_64" ]; then
            OS="UBUNTU-20.04-64: `cat /etc/lsb-release`: 0"
        fi
    fi

    if [ -z "$OS" ]; then
        OS="Unsupported: `cat /etc/lsb-release` `uname -m`: 1"
    fi
elif [ -f /etc/debian_version ]; then
    if grep -q '^7.*' /etc/debian_version; then
        if [ `uname -m` = "x86_64" ]; then
            OS="DEBIAN7-64: `cat /etc/debian_version`: 0"
        fi
    elif grep -q '^8.*' /etc/debian_version; then
        if [ `uname -m` = "x86_64" ]; then
            OS="DEBIAN8-64: `cat /etc/debian_version`: 0"
        fi
    elif grep -q '^9.*' /etc/debian_version; then
        if [ `uname -m` = "x86_64" ]; then
            OS="DEBIAN9-64: `cat /etc/debian_version`: 0"
        fi
    elif grep -q '^10.*' /etc/debian_version; then
        if [ `uname -m` = "x86_64" ]; then
            OS="DEBIAN10-64: `cat /etc/debian_version`: 0"
        fi
    fi

    if [ -z "$OS" ]; then
        OS="Unsupported: Debian `cat /etc/debian_version` `uname -m`: 1"
    fi
fi

if [ $# -gt 0 ]
then
    echo $OS
fi


#################
# DEFAULT VALUES
#################

COMPONENT_TO_BE_BUILT=${1:-UA}
GIT_BRANCH=${2:-develop}
MAJOR_VERSION=${3:-9}
MINOR_VERSION=${4:-50}
PATCH_SET_VERSION=${5:-0}
PATCH_VERSION=${6:-0}
BUILD_QUALITY=${7:-RELEASE}
BUILD_PHASE=${8:-GA}
FTP_BUILD=${9:-no}
shift
CVS_UPDATE=${9:-yes}
shift
GIT_TAG=${9:-develop}
shift
TOP_DIR_FOR_UA=${9:-/BUILDS}
shift
AGENT_TYPE_FOR_UA=${9:-both}
shift
CONFIGURATION_FOR_UA=${9:-both}
shift
BINARIES_PATH_FOR_UA=${9:-/BUILDS/develop/BINARIES/UNIFIED}
shift
TIER_NUMBER=${9:-tier1}
SCRIPTS_PATH_FOR_UA=/BUILDS/SCRIPTS/develop/UNIFIED

case $COMPONENT_TO_BE_BUILT in

	UA)
		for ip in `cat build/scripts/general/iplist`
		do
		    IP=`echo ${ip} | cut -d":" -f1`
		    ssh -f ${IP} "mkdir -p ${BINARIES_PATH_FOR_UA} ${SCRIPTS_PATH_FOR_UA}"
		    sleep 10
		    scp build/scripts/general/${COMPONENT_TO_BE_BUILT}_TRIGGER.sh ${IP}:${SCRIPTS_PATH_FOR_UA}
		    ssh -f $IP "cd ${SCRIPTS_PATH_FOR_UA}; ./${COMPONENT_TO_BE_BUILT}_TRIGGER.sh ${TOP_DIR_FOR_UA} inmage ${GIT_BRANCH} ${GIT_TAG} ${BUILD_QUALITY} ${BUILD_PHASE} ${MAJOR_VERSION} ${MINOR_VERSION} ${PATCH_SET_VERSION} ${PATCH_VERSION} ${AGENT_TYPE_FOR_UA} ${CONFIGURATION_FOR_UA} ${FTP_BUILD} ${TIER_NUMBER} > ${BINARIES_PATH_FOR_UA}/UA_WRAPPER_log 2>&1 "
		done
	;;
esac


#!/bin/sh

##
# Defining the Usage
##
USAGE="Usage:   ./bld_env_setup.sh <Top Build Dir> <type of the agent build>"
[ -z "$1" ] && echo $USAGE && exit 65
[ -z "$2" ] && echo $USAGE && exit 65

##
# Making top dir for build
##
if [ ! -d "$1" ]
then
	mkdir -p $1

	if [ $? -eq 0 ]
	then
		if [ "$2" = "both" ]; then
			mkdir -p ${1}/source ${1}/logs/VX ${1}/logs/FX ${1}/binaries/VX ${1}/binaries/FX > /dev/null 2>&1
			echo "Created directory ${1} and subdirectories source, logs and binaries under it..."
		elif [ "$2" = "FX" ]; then
			mkdir -p ${1}/source ${1}/logs/FX ${1}/binaries/FX > /dev/null 2>&1
			echo "Created directory ${1} and subdirectories source, logs and binaries under it..."
		elif [ "$2" = "VX" ]; then
			mkdir -p ${1}/source ${1}/logs/VX ${1}/binaries/VX > /dev/null 2>&1
			echo "Created directory ${1} and subdirectories source, logs and binaries under it..."
		else
			echo "Directory creation failed for ${1}!"
			exit 66
		fi
	fi
else
	echo "Directory $1 already exists. Attempting to create subdirectories source, logs and binaries under it..."
	CUR_W_D=`pwd`

	cd $1

	if [ $? -eq 0 ]
	then
		if [ "$2" = "both" ]; then
			mkdir -p source logs/VX binaries/VX logs/FX binaries/FX > /dev/null 2>&1
			cd $CUR_W_D
		elif [ "$2" = "FX" ]; then
			mkdir -p source logs/FX binaries/FX > /dev/null 2>&1
			cd $CUR_W_D
		elif [ "$2" = "VX" ]; then
			mkdir -p source logs/VX binaries/VX > /dev/null 2>&1
			cd $CUR_W_D
		fi
	else
		echo "Cannot change directories to ${1}!"
		cd $CUR_W_D
		exit 67
	fi
fi


#!/bin/sh

# Set the required variables.
TOP_BLD_DIR=${1:-`pwd`}
GIT_TAG=${2:-develop}
CLEAN_REPO=${3:-yes}
CHKOUT_LOG="checkout_$GIT_TAG.log"
X_ARCH=`uname -ms | sed -e s"/ /_/g"`
date_suffix=`date +%e_%b_%Y | awk '{print $1}'`

# Change directories to the source folder where checkout will take place.
if [ -d $TOP_BLD_DIR/source ]; then
  CUR_W_D=`pwd`
  cd $TOP_BLD_DIR/source
else
  echo "Directory $TOP_BLD_DIR/source not found."
  exit 1
fi

if [ $CLEAN_REPO == "yes" ]; then
	rm -rf $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery
	if [ $? -eq 0 ]; then
		echo "Successfully deleted $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery directory."
	else
		echo "Failed to delete $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery directory."
		exit 1
	fi
fi

# checkout workarea if it doesn't exist already.
if [ ! -d $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery ]; then
	: > $CHKOUT_LOG

	git clone -b ${GIT_TAG} --single-branch msazure@vs-ssh.visualstudio.com:v3/msazure/One/InMage-Azure-SiteRecovery >> $CHKOUT_LOG 2>&1
	if [ $? -eq 0 ]; then
		echo "Successfully cloned InMage-Azure-SiteRecovery git repo from branch ${GIT_TAG}." >> $CHKOUT_LOG 2>&1
		cd InMage-Azure-SiteRecovery
	else
		echo "Failed to clone InMage-Azure-SiteRecovery git repo and branch ${GIT_TAG}." >> $CHKOUT_LOG 2>&1
		exit 1
	fi
else
		cd InMage-Azure-SiteRecovery
		git checkout ${GIT_TAG}
		if [ $? -eq 0 ]; then
			echo "Successfully checked out code from ${GIT_TAG}." >> $CHKOUT_LOG 2>&1
		else
			echo "Failed to check out code from ${GIT_TAG}." >> $CHKOUT_LOG 2>&1
		exit 1
		fi
fi

# Replacing build switch with all in ubuntu.sh script. Build switch is used in cloud build and all switch is used in on-prem builds.
sed -i -e "s|user_space/build/ubuntu.sh\ build|user_space/build/ubuntu.sh\ all|g" host/vx_setup.mak
if [ $? -eq 0 ]; then
	echo "Replaced build switch with all in ubuntu.sh script." >> $CHKOUT_LOG 2>&1
else
	echo "Failed to replace build switch with all in ubuntu.sh script." >> $CHKOUT_LOG 2>&1
	exit 1
fi

# Provide execute permissions to all files.
find admin/ build/ host/ server/ Solutions/ -type f -exec chmod 755 {} \; >> $CHKOUT_LOG 2>&1
if [ $? -eq 0 ]; then
	echo "Gave execute permission to all files successfully." >> $CHKOUT_LOG 2>&1
else
	echo "Failed to give execute permissions to all files." >> $CHKOUT_LOG 2>&1
	exit 1
fi

# Convert to Unix line endings.
find admin/ build/ host/ server/ Solutions/ -type f -exec dos2unix {} \; >> $CHKOUT_LOG 2>&1
if [ $? -eq 0 ]; then
    echo "Converted to Unix line endings successfully." >> $CHKOUT_LOG 2>&1
else
    echo "Failed to convert to Unix line endings." >> $CHKOUT_LOG 2>&1
    exit 1
fi

# Temporary workaround till depend.sh is fixed.
find admin/ build/ host/ server/ Solutions/ -type f -exec touch {} \; >> $CHKOUT_LOG 2>&1
if [ $? -eq 0 ]; then
    echo "Touched all the files successfully." >> $CHKOUT_LOG 2>&1
else
    echo "Failed to touch files." >> $CHKOUT_LOG 2>&1
    exit 1
fi

# Removing the exiting symbolic links so that the make will create the respective symbolic links.
rm -f ${THIRDPARTY_PATH}/lib/lib ${THIRDPARTY_PATH}/bin/bin

cd $CUR_W_D


#!/bin/sh

##
# Defining different exit codes. This would help track failures better
##

# Exit code table
E_SUCCESS=0
E_GENERIC_FAILURE=1
E_OS_NOT_SUPPORTED=25
E_SETUP_ARG_MISSING=65
E_SETUP_DIRCREATION_FAILURE=66
E_SETUP_CHANGEDIR_FAILURE=67
E_CHECKOUT_ARG_MISSING=75
E_CHECKOUT_SOURCE_DIR_NOT_FOUND=76
E_VERSION_ARG_MISSING=85
E_VERSION_SCRIPT_NOT_FOR_CODE_BRANCH=86
E_VERSION_FAILURE_TO_GET_SECS_ELAPSED=88
E_VERSION_PARTNER_NOT_HANDLED=89
E_VERSION_BIN_DIR_NOT_FOUND=90
E_BUILD_VX_FAILURE=94
E_BUILD_DRIVER_BLD_FAILURE=95
E_BUILD_INMSHUTNOTIFY_FAILURE=99
E_BUILD_SVDCHECK_FAILURE=100
E_BUILD_INMSTKOPSBIN_FAILURE=101
E_BUILD_DRIVER_MACHINE_DOWN=102
E_PACKAGING_BINARIES_ABSENT=105
E_PACKAGING_PARTNER_DIR_ABSENT=106

##
# This function executes a command and logs the output
##
DO_AND_LOG()
{
	CMD=$1
	eval $CMD >> $FLOG
}

##
# This function verifies the exit status of a program and print messages accordingly
##
VERIFY()
{
	status=$1

	case $status in

		$E_SUCCESS) ;;

		$E_OS_NOT_SUPPORTED)
			echo "THIS PLATFORM IS NOT SUPPORTED YET!"
			exit $E_OS_NOT_SUPPORTED ;;

		$E_SETUP_ARG_MISSING)
		   	echo "SOME OR ALL ARGUMENTS FOR vx_bld_env_setup.sh ARE MISSING!"
			exit $E_SETUP_ARG_MISSING ;;

		$E_SETUP_DIRCREATION_FAILURE)
			echo "DIRECTORY $TOP_BLD_DIR COULD NOT BE CREATED!"
			exit $E_SETUP_DIRCREATION_FAILURE ;;

		$E_SETUP_CHANGEDIR_FAILURE)
			echo "FAILED TO CHANGE DIRECTORY TO $TOP_BLD_DIR!"
			exit $E_SETUP_CHANGEDIR_FAILURE ;;

		$E_CHECKOUT_ARG_MISSING)
			echo "SOME OR ALL ARGUMENTS FOR vx_checkout.sh ARE MISSING!"
			exit $E_CHECKOUT_ARG_MISSING ;;

		$E_CHECKOUT_SOURCE_DIR_NOT_FOUND)
			echo "DIRECTORY source NOT FOUND UNDER TOP BUILD DIRECTORY!"
			exit $E_CHECKOUT_SOURCE_DIR_NOT_FOUND ;;

		$E_SCRIPT_NOT_FOR_CODE_BRANCH)
			echo "CODE BRANCH SUPPLIED AS ARGUMENT TO vx_versioning.sh IS NOT VALID FOR THIS SCRIPT!"
			exit $E_SCRIPT_NOT_FOR_CODE_BRANCH ;;

		$E_VERSION_PARTNER_NOT_HANDLED)
			echo "PARTNER SUPPLIED TO vx_versioning.sh NOT HANDLED IN THIS SCRIPT!"
			exit $E_VERSION_PARTNER_NOT_HANDLED ;;

		$E_PACKAGING_PARTNER_DIR_ABSENT)
			echo "DIRECTORY $TOP_BLD_DIR/source/build/$PARTNER NOT FOUND!"
			exit $E_PACKAGING_PARTNER_DIR_ABSENT ;;

	esac
}

usage()
{
	 echo "usage: ./complete.sh [-s <setup/checkout/build_package>] [-d <top build dir>] -T <thirdparty dirpath> [-b <branch>] [ -B <tagname-for-checkout> ] [-p <partner>] [-x <X_ARCH>] [-c <release|debug>] [-v] [-w <none|warn|error>] [-q <DAILY|RELEASE>] [-P <buildphase|DIT] [ -M <Major version> ] [ -N <Minor Version> ] [ -A <Agent Type> ] [-h] <cvs username>"
	 echo "  <cvs username> required: cvs login id used to check source"
	 echo "  -s <setup/checkout/build_package> --> Quit after the stage is finished"
	 echo "  -d <directory to build in> (optional): directory where you want the build done. default current directory"
	 echo "      $DEFAULT_TOP_BLD_DIR"
	 echo "  -b <branch> (optional): cvs branch to use for checking out source and computing build number. default $DEFAULT_CVS_BRANCH"
	 echo "  -B <tagname-for-checkout> (optional): cvs tag to use when checking out source. default $DEFAULT_GIT_TAG"
	 echo "  -p <partner> (optional): partner the build is for. default $DEFAULT_PARTNER"
	 echo "  -x <X_ARCH> (optional): X_ARCH to use for the build. default $DEFAULT_X_ARCH"
	 echo "  -c <release|debug> (optional): configuration to build. default $DEFAULT_CONFIG"
	 echo "  -q <DAILY|RELEASE> (optional): quality of the build (whether daily or release). default $DEFAULT_BLD_QUALITY"
	 echo "  -P <buildphase|DIT> (optional): phase of the build (whether DIT, BETA, etc). default $DEFAULT_BLD_PHASE"
	 echo "  -M < Major Version > default is 9"
	 echo "  -N < Minor Version > default is 0"
	 echo "  -S < Patch Set Version > default is 0"
	 echo "  -V < Patch Version > default is 0"
	 echo "  -A < Agent Type > If FX or VX or both"
	 echo "  -T <thirdparty path> required: path of thirdparty folder"
	 echo "  -v (optional): turn on verbose during build. default off"
	 echo "  -w <none|warn|error> (optional): compiler warning level to use. default $DEFAULT_WARN_LEVEL"
	 echo "               none: use compiler defaults"
	 echo "               warn: add additional warning checks to compiler"
	 echo "               error: add additional warning checks to compiler and treat warnings as errors"
	 echo "  -h (optional): display this help"
	 exit 1
}

parse_cmd_line ()
{
	 if test "$1" = "" ; then
		  echo "cvs username required"
		  usage
	 else
		  while test "$1" != "" ; do
				case $1 in
					 -d)
						  TOP_BLD_DIR="$2"
						  shift
						  ;;
					 -s)
						  STAGE="$2"
						  shift
						  ;;
					 -b)
						  CVS_BRANCH="$2"
						  shift
						  ;;
					 -B)
						  GIT_TAG="$2"
						  shift
						  ;;
					 -p)
						  PARTNER="$2"
						  shift
						  ;;
					 -c)
						  CONFIG="$2"
						  shift
						  ;;
					 -q)
						  BUILD_QUALITY="$2"
						  shift
						  ;;
					 -v)
						  VERBOSE="-v"
						  ;;
					 -h)
						  usage
						  ;;
					 -w)
						  WARN_LEVEL="$2"
						  shift
						  ;;
					 -x)
						  X_ARCH="$2"
						  shift
						  ;;
					 -P)
						  BUILD_PHASE="$2"
						  shift
						  ;;

					 -M)
						 MAJOR_VERSION="$2"
						 shift
						 ;;
					-N)
                                                 MINOR_VERSION="$2"
                                                 shift
                                                 ;;
					-S)
                                                 PATCH_SET_VERSION="$2"
                                                 shift
                                                 ;;

                                        -V)
                                                 PATCH_VERSION="$2"
                                                 shift
                                                 ;;
                                        -A)
                                                 AGENT_TYPE="$2"
                                                 shift
                                                 ;;

					 -T)
						  THIRDPARTY_PATH="$2"
						  if test "$THIRDPARTY_PATH" = ""; then
							echo "Enter thirdparty path"
							usage
						  fi
						  shift
						  ;;
					 -*)
						  echo "invalid option $1"
						  usage
						  ;;
					 *)
						  if test "$CVS_USERNAME" != "" ; then
							echo "invalid option $1"
							usage
						  fi
 						  CVS_USERNAME="$1"
						  ;;
				esac
				shift
		  done
	 fi

	 if test "$CVS_USERNAME" = "" ; then
		  echo "cvs username required"
		  usage
	 fi

}

##
# DEFAULTS
# sets up inital default values that can be over ridden by command line options
# these are used that usage can display the default values even if a command line
# option has already set the value
##
DEFAULT_TOP_BLD_DIR=`pwd`
DEFAULT_CVS_BRANCH="develop"
DEFAULT_GIT_TAG="develop"
DEFAULT_PARTNER="inmage"
DEFAULT_CONFIG="release"
DEFAULT_WARN_LEVEL="none"
DEFAULT_X_ARCH=`uname -ms | sed -e s"/ /_/g"`
DEFAULT_BLD_QUALITY="DAILY"
DEFAULT_BLD_PHASE="DIT"
DEFAULT_STAGE="";
DEFAULT_MAJOR_VERSION=9
DEFAULT_MINOR_VERSION=0
DEFAULT_AGENT_TYPE=both

##
# VARIABLES
# the variables that will be used
# set them to their defaults. note: some maybe over ridden by command line options
##
TOP_BLD_DIR="$DEFAULT_TOP_BLD_DIR"
CVS_BRANCH="$DEFAULT_CVS_BRANCH"
GIT_TAG="$DEFAULT_GIT_TAG"
PARTNER="$DEFAULT_PARTNER"
CONFIG="$DEFAULT_CONFIG"
VERBOSE=yes
WARN_LEVEL="$DEFAULT_WARN_LEVEL"
X_ARCH="$DEFAULT_X_ARCH"
SUFFIX=`date +%d`_`date +%b`_`date +%H`_`date +%M`_`date +%S`
FLOG="$TOP_BLD_DIR/logs/VX_Build_$SUFFIX.log"
CVS_USERNAME=
THIRDPARTY_PATH=
BUILD_QUALITY="$DEFAULT_BLD_QUALITY"
BUILD_PHASE="$DEFAULT_BLD_PHASE"
STAGE=$DEFAULT_STAGE
MAJOR_VERSION="$DEFAULT_MAJOR_VERSION"
MINOR_VERSION="$DEFAULT_MINOR_VERSION"
AGENT_TYPE="$DEFAULT_AGENT_TYPE"

##
# Step 1: COMMAND LINE VALIDATION
# This would capture various parameters passed to this script, validates them and
# sets them to required variables
##
parse_cmd_line $@

##
# Step 1.1: Find out how much needs to be done
# If build_status file is lying around, read it and figure out
# If file does not exist, do everything
# A value of 1 for a step's flag means the step's to be done; a value of 0 means leave that step
# Truncate all slashes in TOP_BLD_DIR so that touch doesn't fail
##

Build_Dir=`echo $TOP_BLD_DIR | sed -e "s/\///g"`

if [ ! -e build_status_${Build_Dir} ]; then
	touch build_status_${Build_Dir}
	SETUP=1 CHECKOUT=1 BUILD_PACKAGE=1
else
	if grep -iq "setup_${AGENT_TYPE}" build_status_${Build_Dir} ; then
		SETUP=0
	else
		SETUP=1
	fi

	if grep -iq "checkout" build_status_${Build_Dir} ; then
		CHECKOUT=0
	else
		CHECKOUT=1
	fi

	if grep -iq "build_package_${PARTNER}_${CONFIG}_${AGENT_TYPE}" build_status_${Build_Dir} ; then
		BUILD_PACKAGE=0
	else
		BUILD_PACKAGE=1
	fi

fi

if [ "$AGENT_TYPE" = "both" ]; then
        argument_for_make=ua_setup
elif [ "$AGENT_TYPE" = "FX" ]; then
        argument_for_make=fx_setup
elif [ "$AGENT_TYPE" = "VX" ]; then
        argument_for_make=vx_setup
fi

##
# Step 2: BUILD ENVIRONMENT SETUP
# Making top dir for build and export common required shell variables
##

if [ $SETUP -eq 1 ]; then
	echo
	echo "Setting up required directory structure..."
	echo
	./bld_env_setup.sh $TOP_BLD_DIR $AGENT_TYPE
	SETUP_EXIT_STATUS=$?
	VERIFY $SETUP_EXIT_STATUS
	echo "setup_${AGENT_TYPE}" >> build_status_${Build_Dir}
else
	echo "Build directory structure setup already done for $TOP_BLD_DIR!"
fi

if [ z"$STAGE" = z"setup" ]; then exit; fi

##
# Step 3: CHECKOUT
# Set variables and checkout files as required on the chosen OS
##

if [ $CHECKOUT -eq 1 ] ; then
	echo
	echo "Checking out source code now..."
	echo
	./checkout.sh $TOP_BLD_DIR $GIT_TAG
	CHECKOUT_EXIT_STATUS=$?
	VERIFY $CHECKOUT_EXIT_STATUS
	echo "checkout" >> build_status_${Build_Dir}
else
	echo "Source code checkout already done for $TOP_BLD_DIR!"
fi

if [ z"$STAGE" = z"checkout" ]; then exit; fi

##
# Step 6: BUILD
##

if [ $BUILD_PACKAGE -eq 1 ] ; then
	echo
	echo "Building the agent now..."
	echo
	cur_wd=`pwd`
	cd $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery/host
	make clean

        if [ "$CONFIG" = "debug" ];then
		BUILD_CONFIG=yes
	elif [ "$CONFIG" = "release" ];then
		BUILD_CONFIG=no
	fi
	gmake $argument_for_make X_VERSION_MAJOR=$MAJOR_VERSION X_VERSION_MINOR=${MINOR_VERSION} X_PATCH_SET_VERSION=${PATCH_SET_VERSION} X_PATCH_VERSION=${PATCH_VERSION} X_VERSION_QUALITY=$BUILD_QUALITY X_VERSION_PHASE=$BUILD_PHASE debug=$BUILD_CONFIG warnlevel=$WARN_LEVEL verbose=$VERBOSE partner=$PARTNER

	BUILD_EXIT_STATUS=$?
	VERIFY $BUILD_EXIT_STATUS
	cd $cur_wd
	echo "build_package_${PARTNER}_${CONFIG}_${AGENT_TYPE}" >> build_status_${Build_Dir}

	# Copy the tar files to binaries directory under TOP_BLD_DIR
	if [ "$AGENT_TYPE" = "both" ]; then
		mv $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery/host/${X_ARCH}/setup/${CONFIG}/*.tar.gz $TOP_BLD_DIR/binaries/FX
		mv $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery/host/${X_ARCH}/setup_vx/${CONFIG}/*.tar.gz $TOP_BLD_DIR/binaries/VX
		mv $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery/host/${X_ARCH}/setup_ua/${CONFIG}/*.tar.gz $TOP_BLD_DIR/binaries
		mv $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery/host/*.tar.gz $TOP_BLD_DIR/binaries

	elif [ "$AGENT_TYPE" = "FX" ]; then
		if [ "$CONFIG" = "release" ];then
			cd $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery/host
			gmake symbol_generation X_VERSION_MAJOR=$MAJOR_VERSION X_VERSION_MINOR=${MINOR_VERSION} X_VERSION_QUALITY=$BUILD_QUALITY X_VERSION_PHASE=$BUILD_PHASE debug=$BUILD_CONFIG warnlevel=$WARN_LEVEL verbose=$VERBOSE partner=$PARTNER
			cd $cur_wd
			mv $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery/host/*.tar.gz $TOP_BLD_DIR/binaries
		fi
		mv $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery/host/${X_ARCH}/setup/${CONFIG}/*.tar.gz $TOP_BLD_DIR/binaries/FX

	elif [ "$AGENT_TYPE" = "VX" ]; then
		if [ "$CONFIG" = "release" ];then
			cd $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery/host
			gmake symbol_generation X_VERSION_MAJOR=$MAJOR_VERSION X_VERSION_MINOR=${MINOR_VERSION} X_VERSION_QUALITY=$BUILD_QUALITY X_VERSION_PHASE=$BUILD_PHASE debug=$BUILD_CONFIG warnlevel=$WARN_LEVEL verbose=$VERBOSE partner=$PARTNER
			cd $cur_wd
			mv $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery/host/*.tar.gz $TOP_BLD_DIR/binaries
		fi
		mv $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery/host/${X_ARCH}/setup_vx/${CONFIG}/*.tar.gz $TOP_BLD_DIR/binaries/VX
	fi
else
	echo "Build and packaging are already done for $TOP_BLD_DIR!"
fi

if [ z"$STAGE" = z"build_package" ]; then exit; fi


#!/bin/sh

umask 0002
VX_VERSION_FILE="/usr/local/.vx_version"
SCRIPT_DIR=$(readlink -f `dirname "$0"`)
INSTALL_LOG_FILE="$SCRIPT_DIR/ua_install.log"
UPGRADE_LOG_FILE="$SCRIPT_DIR/ua_upgrader.log"
CUR_DIR=`pwd`
INSTALLATION_DIR=$(grep ^INSTALLATION_DIR $VX_VERSION_FILE | cut -d"=" -f2 | tr -d " ")
INSTALL_ERROR_JSON="/var/log/InstallerErrors.json"
PAR_DIR=`dirname $SCRIPT_DIR`
GLOB_LOG_DIR="$PAR_DIR/logs"
GLOB_INSTALL_LOG_FILE="$GLOB_LOG_DIR/ua_install.log"
GLOB_UPGRADE_LOG_FILE="$GLOB_LOG_DIR/ua_upgrader.log"

trace_log_message() {
    DATE_TIME=`date '+%Y/%m/%d %H:%M:%S'`
    echo -e "$@"
    echo "${DATE_TIME} : $@ " >> ${UPGRADE_LOG_FILE} 2>&1
}

exit_with_retcode() {
    #Moving to original directory
    cd $CUR_DIR

    trace_log_message "Dumping Job file content in upgrader log file"
    cat $JOB_FILE_PATH >> $UPGRADE_LOG_FILE

    #TODO Upload upgrader and AzureRcmCLi log.
    ${INSTALLATION_DIR}/bin/AzureRcmCli --agentupgradelogsupload --agentupgradelogspath \
        "$SCRIPT_DIR" --agentupgradejobdetails "$JOB_FILE_PATH"

    #Dump data to global log file
    mkdir -p $GLOB_LOG_DIR
    cat $INSTALL_LOG_FILE >> $GLOB_INSTALL_LOG_FILE
    cat $UPGRADE_LOG_FILE >> $GLOB_UPGRADE_LOG_FILE

    exit $1
}

upgrade_mobility_service() {
    trace_log_message "ENTERED $FUNCNAME"

    $SCRIPT_DIR/install -r MS -v VmWare -q -a Upgrade -c CSPrime -l $INSTALL_LOG_FILE \
        -e $INSTALL_ERROR_JSON -j $SCRIPT_DIR/installerjson.json
    local ret_val=$?

    trace_log_message "EXITED $FUNCNAME"
    return $ret_val
}

register_source_agent() {
    trace_log_message "ENTERED $FUNCNAME"
    local ret_val=1
    local count=0

    while [ $count -le 2 ]; do
        trace_log_message "AzureRcmCli registersourceagent operation - iteration : $count"
        trace_log_message "-------------------------------------------------------------"
        trace_log_message "Executing the command : ${INSTALLATION_DIR}/bin/AzureRcmCli " \
            "--registersourceagent --errorfilepath $INSTALL_ERROR_JSON"
        ${INSTALLATION_DIR}/bin/AzureRcmCli --registersourceagent --errorfilepath \
            $INSTALL_ERROR_JSON >> $UPGRADE_LOG_FILE 2>&1
        ret_val=$?
        if [ $ret_val -eq 0 ]; then
            trace_log_message -q "registersourceagent operation has succeeded."
            break
        else
            trace_log_message -q "registersourceagent failed with exit code - $ret_val"
            count=$(expr $count + 1)
            sleep 5
        fi
    done

    trace_log_message "EXITED $FUNCNAME"
    return $ret_val
}

upgrade_action() {
    trace_log_message "ENTERED $FUNCNAME"
    upgrade_mobility_service
    upgrade_ret_val=$?

    if [ $upgrade_ret_val -ne 0 -a $upgrade_ret_val -ne 98 \
        -a $upgrade_ret_val -ne 209 ]; then
        trace_log_message "Upgrade agent failed with return value : $upgrade_ret_val"
        return $upgrade_ret_val
    fi
    register_source_agent
    reg_source_exit_code=$?
    trace_log_message ""
    if [ $reg_source_exit_code -eq 0 ]; then
        trace_log_message "registersourceagent operation has succeeded."
    else
        trace_log_message "registersourceagent failed with exit code - $reg_source_exit_code"
    fi

    trace_log_message "EXITED $FUNCNAME"
    return $reg_source_exit_code
}

complete_job_to_rcm() {
    trace_log_message "ENTERED $FUNCNAME"

    ${INSTALLATION_DIR}/bin/AzureRcmCli --completeagentupgrade --agentupgradeexitcode \
        "$upgrade_action_return_value" --agentupgradejobdetails "$JOB_FILE_PATH" --errorfilepath \
        "$INSTALL_ERROR_JSON" >> $UPGRADE_LOG_FILE 2>&1
    local ret_val=$?

    trace_log_message "EXITED $FUNCNAME"
    return $ret_val
}

post_action() {
    trace_log_message "ENTERED $FUNCNAME"

    complete_job_to_rcm
    post_exit_code=$?
    if [ $post_exit_code -eq 0 ]; then
        trace_log_message "Post actions completed successfully"
    else
        trace_log_message "Post actions failed"
    fi

    trace_log_message "EXITED $FUNCNAME"
    return $post_exit_code
}

main() {
    while getopts :j:  opt
    do
        case $opt in
        j)  JOB_FILE_PATH="$OPTARG"
        ;;
        *)  trace_log_message "Incorrect usage"
            exit_with_retcode 1
        ;;
        esac
    done

    if [ -z "$JOB_FILE_PATH" ]; then
        trace_log_message "Job File not provided"
        exit_with_retcode 1
    fi
    if [ ! -f "$JOB_FILE_PATH" ]; then
        trace_log_message "File path: $JOB_FILE_PATH doesn't exist"
        exit_with_retcode 1
    fi
    #installer needs to be invoked from the same directory
    cd $SCRIPT_DIR

    upgrade_action
    upgrade_action_return_value=$?
    post_action || exit_with_retcode $?
    exit_with_retcode 0
}

main "$@"