#!/bin/sh
##############################################################################
#
#  Copyright (c) 2013, Doremi Labs, Inc.
#    All rights reserved.
#
#  Redistribution in source or binary forms, with or without
#  modification, are NOT permitted.
#
#    Doremi Labs, Inc.
#    1020 Chestnut St.
#    Burbank, CA 91506
#    Tel : (818) 562 1101
#    Fax : (818) 562 1109
#
##############################################################################

if test -e /etc/init.d/drmfunctions; then
	. /etc/init.d/drmfunctions
elif test -e /doremi/etc/init.d/functions; then
	. /doremi/etc/init.d/functions
else
	return 255
fi

PACKAGE="$1"
LOGFILE="/doremi/log/update.log"

echo_log() {
	echo "[$(date)]: pkg_install: $1" >> "${LOGFILE}"
}

install_pkg(){
	local PACKAGE="$1"
	local PACKAGE_NAME=$(basename "${PACKAGE}")
	local PACKAGE_PATH=$(dirname "${PACKAGE}")
	local FOLDER="${PACKAGE_PATH}/update_$$"
	local PWD_BEFORE=$(pwd)
	local isError=0

	echo_log "Installing embedded package '${PACKAGE_NAME}' ..."

	if ! test -r "${PACKAGE}"; then
		echo_log "ERROR: package does not exist: ${PACKAGE}"
		isError=1
	elif ! mkdir -p "${FOLDER}" > /dev/null 2>&1; then
		echo_log "ERROR: failed to create directory: ${FOLDER}"
		isError=1
	elif ! cd "${FOLDER}" &> /dev/null; then
		echo_log "ERROR: failed to change directory to ${FOLDER}"
		isError=1
	elif ! tar zxvf "${PACKAGE}" > /dev/null 2>&1; then
		echo_log "ERROR: failed to extract package in ${FOLDER}"
		isError=1
	elif ! rm -f "${PACKAGE}" &> /dev/null; then
		echo_log "ERROR: failed to delete package ${PACKAGE}"
		isError=1
	elif ! test -f install.sh; then
		echo_log "ERROR: invalid package: install.sh does not exist"
		isError=1
	elif ! chmod 0755 install.sh > /dev/null; then
		echo_log "ERROR: failed to change permissions of install.sh"
		isError=1
	else
		./install.sh
		isError=$?

		if [ "${isError}" -ne 0 ]; then
			echo_log "ERROR: package installation has failed (error code: ${isError})"
		fi
	fi

	# Return to original directory
	cd "${PWD_BEFORE}"

	rm -rf "${FOLDER}" > /dev/null 2>&1

	return ${isError}
}

#
# main()
#

install_pkg "${PACKAGE}"

exit $?

