#!/bin/sh
# Copyright (c) 2000-2011 Synology Inc. All rights reserved.

# customized items of package
if [ -z "$SYNOPKG_PKGNAME" ]; then
        # prior DSM 3.2, start script will be run without environment variable
        #  at boot time, thus we need a workaround to gather name and version info
        PACKAGE_NAME="iTunesServer"
        PACKAGE_VER=`get_key_value "/var/packages/${PACKAGE_NAME}/INFO" "version"`
else
        PACKAGE_NAME=$SYNOPKG_PKGNAME
        PACKAGE_VER=$SYNOPKG_PKGVER
        PACKAGE_DEST=$SYNOPKG_PKGDEST
fi


PACKAGE_DIR="/var/packages/iTunesServer"
PACKAGE_CONFIG_MIGRATE_SH="/usr/syno/bin/package_config_migrate.sh"
DELETE_SYNOINFO_KEYS="supportitunes runitunes"
SERVICETOOL="/usr/syno/bin/servicetool"
PKG_STATUS=$SYNOPKG_PKG_STATUS

install_etc_and_initial() {

	if [ -f "/etc/mt-daapd.conf" ]; then
		cp -rf /etc/mt-daapd.conf "${PACKAGE_DIR}"/etc/mt-daapd.conf
		rm /etc/mt-daapd.conf
	fi
}

upgradesetting() {
	$PACKAGE_CONFIG_MIGRATE_SH del "/etc/synoinfo.conf" "$DELETE_SYNOINFO_KEYS"
}

install_port_setting()
{
	local PortFilePath="${PACKAGE_DIR}/target/etc/synoitunes_port"

	# add port-forwarding config file
	${SERVICETOOL} --install-configure-file --package ${PortFilePath}
}

install_synosdk_servicehook_plugin()
{
	local dlScriptsPach="${PACKAGE_DIR}/target/scripts"
	local destservicecommon="/usr/local/libexec"
	local destservice="/usr/local/libexec/service"

	if [ ! -d ${destservicecommon} ]; then
		mkdir -p ${destservicecommon}
	fi
	ln -s "${dlScriptsPach}/iTunesServiceCommon.sh" "${destservicecommon}/iTunesServiceCommon.sh"
	if [ ! -d ${destservice} ]; then
		mkdir -p ${destservice}
	fi
	cp -f "${dlScriptsPach}/synoitunes_service.sh" "${destservice}/synoitunes_service.sh"
}

install_etc_and_initial
upgradesetting
install_port_setting
install_synosdk_servicehook_plugin

# prepare index config file
INDEX_PACKAGE_PATH=/usr/syno/etc/synoindex/packages/${PACKAGE_NAME}
if [ ! -d ${INDEX_PACKAGE_PATH} ]; then
       mkdir -p ${INDEX_PACKAGE_PATH}
fi

#Stop related daemons
/usr/syno/etc.defaults/rc.d/S66synoindexd.sh stop
/usr/syno/etc.defaults/rc.d/S77synomkthumbd.sh stop
/usr/syno/etc.defaults/rc.d/S88synomkflvd.sh stop

#Install INFO
cp -rf ${PACKAGE_DEST}/etc/index/INFO ${INDEX_PACKAGE_PATH}/INFO

#Start related daemons
/usr/syno/etc.defaults/rc.d/S66synoindexd.sh start
/usr/syno/etc.defaults/rc.d/S77synomkthumbd.sh start
/usr/syno/etc.defaults/rc.d/S88synomkflvd.sh start

if [ "INSTALL" == "$PKG_STATUS" ]; then
    /usr/syno/bin/synoindex -R media > /dev/null 2>&1
fi

exit 0
