#!/bin/sh
KEYWORD=gallery
PHPMYSQLPATH=`grep "PHP-MySQL-phpMyAdmin" /etc/zyxel/pkg_conf/status |grep "Installed-Rule" |awk -F":" '{print $2}' |sed 's/\/$//g' |sed 's/ //g'`
GYINSTPATH=`grep "gallery" /etc/zyxel/pkg_conf/status |grep "Installed-Rule" |awk -F":" '{print $2}' |sed 's/\/$//g' |sed 's/ //g'`
MYSQLPATH=${PHPMYSQLPATH}/mysql/bin
BACKUP_PATH=/i-data/.system/zy-pkgs/tmp/PKG_Backup
PKGGUIPATH="/i-data/.system/zy-pkgs/pkggui"

chmod -R 777 $GYINSTPATH/mysql/var/
chmod -R 777 $GYINSTPATH/gui/$KEYWORD/modules/
chmod -R 777 $GYINSTPATH/gui/$KEYWORD/var/
chmod -R 777 $GYINSTPATH/gui/$KEYWORD/themes/

if [ -d $BACKUP_PATH/$KEYWORD ]; then
	# Fixed bug: User can't change admin's password after upgrading FW
	cp -a $GYINSTPATH/gui/$KEYWORD/modules/user/controllers/users.php $BACKUP_PATH/$KEYWORD/modules/user/controllers
	#
	cp -a $BACKUP_PATH/$KEYWORD/var $GYINSTPATH/gui/$KEYWORD
	cp -a $BACKUP_PATH/$KEYWORD/modules $GYINSTPATH/gui/$KEYWORD
	cp -a $BACKUP_PATH/$KEYWORD/themes $GYINSTPATH/gui/$KEYWORD
	cp -a $BACKUP_PATH/$KEYWORD/$KEYWORD $PHPMYSQLPATH/mysql/data
	rm -rf $BACKUP_PATH/$KEYWORD
else
#Copy the default database to mysql
	cp -a ${GYINSTPATH}/gui/gallery/gallery ${PHPMYSQLPATH}/mysql/data
fi

if [ -e $MYSQLPATH/mysqlcheck ]; then
	$GYINSTPATH/etc/init.d/gallery disable
	${PHPMYSQLPATH}/mysql/bin/myisamchk -of ${PHPMYSQLPATH}/mysql/data/gallery/*MYI
else
	sleep 10
	$GYINSTPATH/etc/init.d/gallery disable
	${PHPMYSQLPATH}/mysql/bin/myisamchk -of ${PHPMYSQLPATH}/mysql/data/gallery/*MYI
fi

#Hank add to copy GUI
cp -af ${GYINSTPATH}/gui/${KEYWORD}_gui ${PKGGUIPATH}/${KEYWORD}

#Add the portal cmd
/usr/local/upnp/install_upnpDB.sh GALLERY_HTTP 5000 'http://ip:port/pkg/gallery' 'This web-based application allows your NAS to host pictures. Use the NAS administrator credentials to log in. The administrator can then create accounts for other users.'
/usr/local/upnp/install_upnpDB.sh GALLERY_HTTPS 5001 'https://ip:port/pkg/gallery' 'This web-based application allows your NAS to host pictures. Use the NAS administrator credentials to log in. The administrator can then create accounts for other users.'


#Hank add to create the link to call PKG startrp and shutdown script
rm /i-data/.system/zy-pkgs/gallery
ln -sf /usr/local/zy-pkgs/etc/init.d/gallery /i-data/.system/zy-pkgs/gallery
