#!/bin/bash
#
# VERSION=1
# CHANGES="move php-cgi to /home/admin during init process; force again symlink to libcrypto/libssl"

# global variables #
BEROCONF=/usr/fallback/beroconf
export PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/fallback"

## udhcpc link to busybox
## the link should be removed from REM_LIST of VERSION.rootfs
## but if package missing from mtdblock7, the udhcpc link/script is always removed
## without beeing replaced by the one present in the package.
## so, we removing the link is managed only here since this part now is only executed if the
## package exists in mtdblock7
if [ -L /sbin/udhcpc ]; then
	mount -o remount,rw /
	rm -rf /sbin/udhcpc
	mount -o remount,ro /
fi

## move php-cgi from mtdblock5 (/) to mtdblock7 (/home/admin)
## upgrade from 20.05 (and lower) to 21.02 (and higher)
if [ ! -f /home/admin/bin/php-cgi ]; then
	minimal=2500
	available=$(/bin/df | /bin/grep /home/admin | /usr/bin/awk '{ print $4; }')
	## check if enough space
	if [ ${available} -lt ${minimal} ]; then
		diff=$(expr ${minimal} - ${available})
		${BEROCONF} set root rootfs-phpcgi-failed FREEING_ROOTFS_FAILED:HOMEADMIN_NOTENOUGH_SPACE:${diff}
	## move php-cgi
	else
		IS_FREED=0
		mount -o remount,rw /home/admin
		mkdir -p /home/admin/bin
		mount -o remount,rw /
		if cp /usr/bin/php-cgi /home/admin/bin; then
			if [ "$(/usr/bin/md5sum /usr/bin/php-cgi | /usr/bin/awk '{ print $1; }')" = "$(/usr/bin/md5sum /home/admin/bin/php-cgi | /usr/bin/awk '{ print $1; }')" ]; then
				## force to remount several times / to avoid unexpected behavior
				mount -o remount,rw /
				rm /usr/bin/php-cgi
				sleep 1; sync; sleep 1
				mount -o remount,rw /
				ln -sf /home/admin/bin/php-cgi /usr/bin
				IS_FREED=1
			fi
		fi
		if [ "${IS_FREED}" = "0" ]; then
			rm /home/admin/bin/php-cgi
			${BEROCONF} set root rootfs-phpcgi-failed FREEING_ROOTFS_FAILED:HOMEADMIN_NOTENOUGH_SPACE
		fi
		mount -o remount,ro /
		mount -o remount,ro /home/admin
	fi
fi

## mounting mtd5 space
mount -oremount,rw /
