#!/bin/sh

# Prepare parameters
pkgtype="critical patch"
build=32360
serial=32360
# Required build number before installing this package
depBuild=32280
# Required package name before installing this package
depPackage="Patch 3"
service_pack=0
version="7.0"
PS_CMD="ps -ef --width 1000"
product="InterScan(TM) Messaging Security Appliance (IMSA)"

GREETING="Installing $product $version $pkgtype $serial"

CheckInstalledIMSS()
{
    IMSSNoExist="0"
    IMSSCCExist="1"
    IMSSEUQExist="1"
    IMSSSDExist="1"
    IsParent="0"
    
#    rpm -q imsscctrl > /dev/null 2>&1
#    if [ $? -eq 0 ] ; then
#      IMSSNoExist="0"
#      IMSSCCExist="1"
#    fi
#    rpm -q imss > /dev/null 2>&1
#    if [ $? -eq 0 ] ; then
#      IMSSNoExist="0"
#      IMSSSDExist="1"
#    fi
#    rpm -q imsseuq > /dev/null 2>&1
#    if [ $? -eq 0 ] ; then
#      IMSSNoExist="0"
#      IMSSEUQExist="1"
#    fi
#    rpm -q ipprofiler > /dev/null 2>&1
#    if [ $? -eq 0 ] ; then
#      IMSSNoExist="0"
#    fi
#    rpm -q nrs > /dev/null 2>&1
#    if [ $? -eq 0 ] ; then
#      IMSSNoExist="0"
#    fi
    
    master_ip=`grep master_ip= /opt/trend/imss/config/slave.nfo | awk -F '=' '{print $2}'`
    if [ "$master_ip" == "" ] ; then
      IsParent="1"
    fi
}

inst_dir=""
inst_version=""
GetInstallPath()
{   
    if [ "$IMSSSDExist" = "1" ]; then
      rpm_check_name="IMSA"
    fi
    
    inst_dir="/opt/trend/imss"
    inst_version=7.0
    
    if [ "$inst_version" != "$version" ] ; then
      echo "$product $version was not found."
      echo "Installation cancelled. No changes were made to your system."
      exit 1
    fi
}

# install/rollback check
PRE_CHECK()
{
  echo "===== Checking system condition ====="
  # if backup dir exist means the cp has already been installed
  if [ "$pkgtype" = "critical patch" ]; then
     if [ ! -d $back_dir ]; then
        # the cp hasn't installed, but if the latest hf build number is greater than cp, there is no need to install this cp
        if [ $build -le $exist_hf ]; then
       	   echo "Your system has already installed the solution in this $pkgtype.  There is no need to install this $pkgtype."
       	   echo "Installation cancelled. No changes were made to your system."
       	   echo
           exit 0
        # The cp may require a previous patch or service pack.
        elif [ $exist_hf -lt $depBuild ]; then
           echo "Please install $depPackage before applying this $pkgtype."
       	   echo "Installation cancelled. No changes were made to your system."
       	   echo
           exit 0        
        # the cp hasn't installed, and the latest hf build number is not greater than cp, it should be installed.
        else    	
       	   echo "Start installing ..."
       	   is_install=1
        fi
     else
     # the cp has installed.
        if [ $exist_hf -ge $build ]; then
           echo "The current hot fix $exist_hf is more recent than this $pkgtype."
           echo "Rollback cancelled. No changes were made to your system."
           echo
           exit 0
        else           
           echo "All the files in this package are up to date."
           is_rollback=1
        fi
     fi
  fi
}

StopServices()
{
  echo
  echo "===== stop imsa services ====="
  ${inst_dir}/script/imssctl.sh stop 
}

StartServices()
{
  echo
  echo "===== start imsa services ====="
  ${inst_dir}/script/imssctl.sh start
}

# Backup
# need modified.
BACKUP()
{
  local local_dir
  local local_file  
  echo 
  echo "===== backing up ====="  
  mkdir -p $back_dir
  echo "Backing up changed files to $back_dir"
  for file in `find . -type f ! \( -name "imssinst" -o -name "EULA.txt" \)`
  do
    local_dir=`dirname $file`
    local_dir=${local_dir#./}
    local_file=`basename $file`
    [ ! -d $back_dir/$local_dir ] && mkdir -p $back_dir/$local_dir
    cp -pf $inst_dir/$file $back_dir/$local_dir
  done
}


# Replace
# need modified.
REPLACE()
{
  local local_dir
  local local_file
  echo 
  echo "===== replacing files ====="  
  fcount=0
  for file in `find . -type f ! \( -name "imssinst" -o -name "EULA.txt" \)`
  do
    local_dir=`dirname $file`
    local_dir=${local_dir#./}
    local_file=`basename $file`
    echo "copy $local_file ---> $inst_dir/$local_dir"
    cp -f $file $inst_dir/$local_dir
    fcount=$(( $fcount + 1 ))
  done
  echo "$fcount files copied"
}

# Change Settings ( ini, pni )
CH_SETTING()
{
  echo 
  echo "===== updating configure files ====="  
  
  
  # update ini setting  
  if [ "$pkgtype" = "critical patch" ] ; then
     if [ $is_install = "1" ]; then
        echo "Recording ${build} to $cp_ini_file"
        echo "${build}" >> $cp_ini_file
     fi
     if [ $is_rollback = "1" ]; then        
        echo "Removing ${build} from cphistory"
        cp_ini_bak=$inst_dir/patch/cphistory.bak
        cat $cp_ini_file |grep -v "${build}" > $cp_ini_bak
        mv -f $cp_ini_bak $cp_ini_file
     fi
  fi
  
}

# Install
INSTALL()
{
   StopServices
   BACKUP
   REPLACE
   CH_SETTING
   StartServices
   echo
   echo "Installation is complete and related services are started." 
   exit 0
}

ROLLBACK()
{
   local local_dir
   local local_file
   echo
   echo "===== rolling back ====="
   StopServices
   fcount=0
   for file in `find . -type f ! \( -name "imssinst" -o -name "EULA.txt" \)`
   do
     local_dir=`dirname $file`
     local_dir=${local_dir#./}
     local_file=`basename $file`
     echo "Rolling back $local_file"
     cp -f $back_dir/$file $inst_dir/$local_dir
     fcount=$(( $fcount + 1 ))
   done
   echo "$fcount files rolled back"  
   CH_SETTING    
   rm -rf $back_dir
   StartServices
   echo
   echo "Rollback is complete and related services are started." 
   exit 0
}
GET_HFNUM()
{
    exist_hf=""
    [ ! -d ${inst_dir}/patch -o ! -f ${inst_dir}/patch/patch.ini ] && exist_hf="0" && return 0
    exist_hf=`cat ${inst_dir}/patch/patch.ini |grep BuildNum|tail -1`
    exist_hf=${exist_hf##*.}"0"
    return 0
}

############### MAIN ##############
umask 22
# require root permission
id | grep root > /dev/null 2>&1
if [ $? -ne 0 ] ; then
  echo "Please log on as a superuser (root) to run this script."
  exit 1
fi

# remember current directory
curr_dir=`pwd`
if [ ! -f $curr_dir/imssinst ]; then
   echo "Files required by the $pkgtype were not found. Installation exits."
   echo "Please go to the folder where $pkgtype files were extracted and run \"./imssinst\"."
   exit 1
fi
export curr_dir

CheckInstalledIMSS
if [ "$IMSSNoExist" = "1" ]; then
   echo "$product $version was not found."
   echo "Installation cancelled. No changes were made to your system."
   exit 1
#elif [ "$IsParent" = "0" ]; then
#   echo "This is not a $product $version parent device, do not need to apply this $pkgtype."
#   echo "Installation cancelled. No changes were made to your system."
#   exit 1
fi

echo $GREETING
echo

# check scheduled update
$PS_CMD | grep imssausched | grep -v grep > /dev/null
if [ $? = 0 ]; then
   echo "Scheduled update is in progress. Please wait until it is finished."
   echo "Installation exits."
   exit 1
fi

# Check if installation path is correct
GetInstallPath

# Set up backup directory
back_dir=${inst_dir}/patch
if [ "$pkgtype" = "hotfix" ] ; then
  back_dir=${back_dir}/Hotfix_B${build}
elif [ "$pkgtype" = "patch" ] ; then
  back_dir=${back_dir}/Patch${serial}_B${build}
elif [ "$pkgtype" = "sp" ] ; then
  back_dir=${back_dir}/SP${serial}_B${build}
elif [ "$pkgtype" = "critical patch" ] ; then
  back_dir=${back_dir}/CP_B${build}
fi

# Get the lastest hf number
GET_HFNUM

cp_ini_file=${inst_dir}/patch/cphistory

# Check install/rollback precondition
is_install=0
is_rollback=0
PRE_CHECK

if [ $is_install -eq "1" ]; then
   INSTALL
fi

if [ $is_rollback -eq "1" ]; then
  ans="n"
  echo "Do you want to roll back $pkgtype $serial? [y/n]"
  read ans
  if [ "$ans" = "y" -o "$ans" = "Y" ]; then
     ROLLBACK
  fi     
fi

exit 0
