#!/bin/bash
# $Id: sm_execute_update,v 1.1 2013/10/16 15:19:08 sesam Exp $
set -x
unitfile="/lib/systemd/system/sepsesam.service"

read_ini()
{
   SM_INI=`grep -i '^sm_ini=' /etc/sesam2000.ini 2>/dev/null|cut -d"=" -f2`
   echo `grep -i "^$1=" "$SM_INI" 2>/dev/null|cut -d"=" -f2-`
}
echo "Starting update: $1"

[ "$2" = "-f" ] && force="--force"
if [ -r  ${unitfile} ]
then
  grep -q ^KillMode= ${unitfile} && sed -i 's/^KillMode=.*/KillMode=process/' ${unitfile} || sed -i '/ExecStop=.*/a KillMode=process' ${unitfile}
  systemctl daemon-reload
fi

gv_rw_work=`read_ini gv_rw_work`
if echo "$1" | grep -q 'deb$'
then
  dpkg -i "${gv_rw_work}/$1"
  iSts=$?
elif echo "$1" | grep -q 'rpm$'
then
  echo "Check, if update can be done by RPM directly..."
  rpm -U ${force} --test "${gv_rw_work}/$1" 
  iSts=$?
  if [ "$iSts" = "0" ]
  then
     echo "Start update by RPM command: rpm -U -vvv ${force} ${gv_rw_work}/$1"
     rpm -U -vvv ${force} "${gv_rw_work}/$1" >>/tmp/sesam_update_rpm.log 2>&1
  else
     if type zypper >/dev/null 2>&1  
     then
       echo "Direct update by RPM does not work. Retry using 'zypper'..."
       zypper install -y "${gv_rw_work}/$1"
     fi
  fi
  iSts=$?
elif echo "$1" | grep -q 'sh$'
then
  "${gv_rw_work}/$1"
  iSts=$?
else
  echo "STATUS=ERROR MSG=Unkown package type"
  exit 2
fi  
if [ "$iSts" = "0" ]
then
  echo "STATUS=SUCCESS MSG=Updated"
else
  echo "STATUS=ERROR MSG=Not updated"
fi
exit $iSts
