#!/bin/bash

UFS_ROOT=/home/admin
PKG_NAME=${1}
PKG_PATH=/apps/${PKG_NAME}

PREFIX="[userapp] uninstall"

if [ -z ${PKG_NAME} ]; then
	echo "${PREFIX}: package name empty => nothing to uninstall, leaving."
	exit 1
fi

if [ ! -d ${PKG_PATH} ]; then
	echo "${PREFIX}: installation directory of package does not exist, leaving."
	exit 1
fi

echo "${PREFIX}: stopping userapp-services."
/etc/init.d/S91userapp stop

mount -oremount,rw ${UFS_ROOT} || exit 1

if [ -x ${UFS_ROOT}/setup/pre_remove.sh ]; then
	echo "${PREFIX}: running pre_remove-script for package ${PKG_NAME}."
	${UFS_ROOT}/setup/pre_remove.sh ${PKG_NAME}
fi

echo "${PREFIX}: removing ${PKG_PATH}."
rm -rf ${PKG_PATH}

echo "${PREFIX} updating PATH-variable in .bash_profile."
for i in $(ls /apps/); do
	path_str_bin="${path_str}:/apps/${i}/bin"
	path_str_lib="${path_str}:/apps/${i}/lib"
done
path_str_bin=$(echo ${path_str_bin} | sed -e 's/\([[\/.*]\|\]\)/\\&/g')
path_str_lib=$(echo ${path_str_lib} | sed -e 's/\([[\/.*]\|\]\)/\\&/g')
sed "s/APPS_PATHS/${path_str_bin}/g" ${UFS_ROOT}/bash_profile_skel > /tmp/admin_bash_profile.tmp
sed "s/LIBS_PATHS/${path_str_lib}/g" /tmp/admin_bash_profile.tmp > ${UFS_ROOT}/.bash_profile
rm -f /tmp/admin_bash_profile.tmp
chown admin:admin ${UFS_ROOT}/.bash_profile

echo "${PREFIX}: wait and sync."
sleep 1; sync; sync; sleep 1

mount -oremount,ro ${UFS_ROOT} || exit 1

echo "${PREFIX}: starting userapp-services."
/etc/init.d/S91userapp start
