#!/bin/bash
#
VERSION='$Id: sm_check_version,v 1.22 2013/10/07 08:46:31 sesam Exp $'
VERBOSE=$1
VERBOSE='-v'
MYSELF=$0
#
trap '' 1 2 3 4 5 6 15

#
# READ INI
read_ini()
{
  SM_INI=$( grep -i '^sm_ini=' /etc/sesam2000.ini|cut -d '=' -f2 )
  echo $( grep -i "$1=" "$SM_INI"|cut -d"=" -f2 )
}

#
# VERBOSE
my_echo()
{
  if [ "$VERBOSE" = "-v" ] 
  then
    echo $(date +"%Y-%m-%d %H:%M:%S"): "$1" >&2
  fi
}

check_version()
{
  my_echo "Check for new sesam version"
  my_echo "Check for systemd invocation id: $INVOCATION_ID"
  export INVOCATION_ID
  SMINI="${GV_RW_INI}/sm.ini"
  gitid_inst=$( grep "^git_id=" "${GV_RW_INI}/sm.ini"|cut -d " " -f 1|cut -d "=" -f 2 )
  gitid_kit=$( grep git_id= $( ls -atr ${GV_RO}/skel/linux_???.5.2*|tail -n1 ) |cut -d " " -f 1|cut -d "=" -f 2 )
  insttype=$( grep "^version=" "${SMINI}" |cut -d '=' -f 2|cut -d ',' -f 1 )
  "${GV_RO_BIN}/sm_update" check
  if [ "$?" = "0" ]; then
     my_echo "No new SEPsesam version found"
     my_echo "Check build id: $gitid_inst <> $gitid_kit"
     if [ "$gitid_inst" = "$gitid_kit" ]; then
        my_echo "Update patch level"
        "${GV_RO_BIN}/sm_update" update -s Service
        return
     fi
     my_echo "Build id has changed. Enforce update ($gitid_inst <> $gitid_kit)"
  fi
  if [ "$insttype" = "server" ];then
      rm -f "${GV_RW_TMP}/sesam_db.sql"
      #psql -d sesam_db -p ${GV_DB_PORT} -U sesam -c "alter system set unix_socket_permissions='0770'"
      #psql -d sesam_db -p ${GV_DB_PORT} -U sesam -c "alter system set unix_socket_group='sesam'"
      "${GV_RO_BIN}/sm_db_update" update -F
      STATUS=$?
      if [ "$STATUS" != "0" ];then
          my_echo "ERROR: Update failed. Exit status from sm_db_update: $STATUS"
      fi    
      "${GV_RO_BIN}/sm_main" stop
  else
      "${GV_RO_BIN}/sm_update" update
      if [ "$insttype" = "tapeserver" -a -r "${GV_RW_INI}/sm_sis.ini" ];then
          "${GV_RO_BIN}/sm_create_sds.sh" -U -Y
      fi
      "${GV_RO_BIN}/sm_update" update
  fi
  return $STATUS
}


#
#
# USAGE
usage()
{
  echo "   $VERSION"
  echo "   usage: $0 [-v] start|stop"
  echo "   default mode start"
  exit 1
}
#
#
sub_env()
{
   GV_RW_LGC=$( read_ini gv_rw_lgc )
   export GV_RW_LGC
   LOGFILE="${GV_RW_LGC}/sm_check_version.log"
   my_echo "VERSION=$VERSION"
   GV_RO_BIN=$( read_ini gv_ro_bin )
   GV_RW_TMP=$( read_ini gv_rw_tmp )
   GV_RW_INI=$( read_ini gv_rw_ini )
   GV_RO=$( read_ini gv_ro )
   GV_RW=$( read_ini gv_rw )

   export GV_RW
}
#

# main()
my_echo "$0 $*"
sub_env "$1" "$2"
check_version 2>&1 </dev/null | tee -a "${LOGFILE}"  2>&1 
STATUS=${PIPESTATUS[0]}

if [ "$STATUS" = "2" ];then
   STATUS=1  #for systemd
   my_echo "STATUS=ERROR MSG=Sesam update failed"
fi
exit $STATUS

