#!/bin/sh
# When you upgrade a package, the Package Center program calls this script before uninstalling the old one.

# First stop naviserver if running

/var/packages/ArchiwareP5/target/stop-server

# DSM Version file
. /etc.defaults/VERSION

if [ "$majorversion" -eq "5"  ]; then
        #pid of Archiware P5 nsd process, to check if archiware is running or not
        NSDPID="$(ps -w | grep /ArchiwareP5/target/bin/nsd | grep -v grep)"
elif [ "$majorversion" -eq "6"  ]; then
        NSDPID="$(ps -ax | grep /ArchiwareP5/target/bin/nsd | grep -v grep)"
fi

if [ -n "$NSDPID" ]; then
    echo "P5 could not be stopped normally, please kill nsd processes manually and try again" > $SYNOPKG_TEMP_LOGFILE
    exit 1
fi

# Target directory where the package is stored.
INSTALL_DIR=$SYNOPKG_PKGDEST
# Volume where package is installed
PKG_VOLUME=$SYNOPKG_PKGDEST_VOL

# The backup directory
BACKUP_DIR=$SYNOPKG_TEMP_UPGRADE_FOLDER
#BACKUP_DIR="$PKG_VOLUME/@p5_backup"
#if [ -d "$BACKUP_DIR" ]; then
#        rm -rf "$BACKUP_DIR"
#        exit_stat=${?}
#        if [ "$exit_stat" -ne "0" ]; then
#                echo "Can't clean backup directory $BACKUP_DIR"
#        fi
#fi
#mkdir "$BACKUP_DIR"
#exit_stat=${?}
#if [ "$exit_stat" -ne "0" ]; then 
#    echo "Can't create backup directory $BACKUP_DIR"
#fi

# Reserved space for P5 in KB
RESERV_SPACE=102400 # 100 MB
# Diretories which need to remain during update
CONFIG_DIR="$INSTALL_DIR/config"
LOG_DIR="$INSTALL_DIR/log"

# Check volume free space (KB)
FREE_SPACE=$( df "$PKG_VOLUME" | sed 1d | awk '{print $4}' )
# Check config files disk usage (KB)
CONFIG_USAGE=$( du -s "$CONFIG_DIR" | awk '{print $1}' )
# Check log files disk usage (KB)
LOG_USAGE=$( du -s "$LOG_DIR" | awk '{print $1}' )
# Required space in KB
KB_REQUIRED=$(($CONFIG_USAGE + $LOG_USAGE + $RESERV_SPACE))
# Required space in MB
MB_REQUIRED=$(($KB_REQUIRED / 1024))

if [ "$KB_REQUIRED" -ge "$FREE_SPACE" ]; then
	echo "Required is $MB_REQUIRED MB and on $PKG_VOLUME is not enough free space for upgrade. Please free some space and try again!" > $SYNOPKG_TEMP_LOGFILE
	exit 1
else
	# Copy log and config folder to temporary location
	exit_msg=$( cp -fR $CONFIG_DIR $LOG_DIR $BACKUP_DIR )
	exit_stat=${?}
	if [ "$exit_stat" -ne "0" ]; then
	   echo "Error occured during backing up configuration files! Please try again!" > $SYNOPKG_TEMP_LOGFILE
	   exit 1
	fi
fi

exit 0
