#!/bin/bash
#
# preinst script
# This script executes before that package will be unpacked from its archive file.
#
# The following environment variables can be used to obtain information about the current installation:
#   PRODUCT_ID, PRODUCT_TYPE, PRODUCT_VERSION, PACKAGE_VERSION, CLIENT_DATA_DIR, DEPOT_ID

TMP_DIR=${CLIENT_DATA_DIR}/../${PRODUCT_ID}.tmp

if [ -d $TMP_DIR ]; then
	echo "Temporary directory $TMP_DIR already exist, aborting!" 1>&2
	exit 1
fi

[ ! -d $CLIENT_DATA_DIR ] && mkdir $CLIENT_DATA_DIR
mkdir $TMP_DIR

if [ -d $CLIENT_DATA_DIR ]; then
	echo "Is unattend.xml identical to template ?..."
	if [ -e $CLIENT_DATA_DIR/custom/unattend.xml ] ; then
		if [ -e $CLIENT_DATA_DIR/opsi/unattend.xml.template ] ; then
			diff $CLIENT_DATA_DIR/custom/unattend.xml $CLIENT_DATA_DIR/opsi/unattend.xml.template &> /dev/null
			if [ $? -eq 0 ]; then
				echo "Removing unchanged unattend.xml..."
				rm $CLIENT_DATA_DIR/custom/unattend.xml
			fi
		fi
	fi
	echo "Saving previous directories..."
	for dirname in drivers opsi custom installfiles* winpe*; do
		for path in $CLIENT_DATA_DIR/$dirname; do
			if [ -e $path ]; then
				echo "   moving $path to $TMP_DIR"
				mv $path $TMP_DIR/ || exit 1
			fi
		done
	done
fi


# save current possible values of property installfiles_dir
property_id="installfiles_dir"
echo $(opsi-admin -S -d method productProperty_getObjects [] "{\"propertyId\":\"$property_id\",\"productId\":\"$PRODUCT_ID\", \"productVersion\": \"$PRODUCT_VERSION\", \"packageVersion\": \"$PACKAGE_VERSION\"}" | awk -F "[=]" -v replace="'" '$1 == "possibleValues" { gsub(replace, "\"", $2); gsub(",","",$2); print  substr($2, 2, length($2)-2) }') > /tmp/current_installfiles

exit 0

