#!/bin/bash
#
#VERSION=3
#CHANGES="disable curl on php.ini for php7; edit: fixing issue"

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

source /usr/fallback/helper

# functions #
function log {
	permlog "pkginst-rootfs-${2}" "[pkginst_rootfs_post]" "${1}"
}

# main #
ROOTFS_VERSION_NEW=${1}
ROOTFS_VERSION_OLD=${2}

if [ -z "${ROOTFS_VERSION_OLD}" ]; then
	ROOTFS_VERSION_OLD=1
fi

## removing ugly reminiscence (aka, issue from old firmware)
#### libcrypto / libssl: symlink issue when libcryto / libssl missing
#### not clearing /home/admin before untaring firmware leads to merge two /etc/init.d files
for file in "/etc/init.d/S43provisioning" "/etc/init.d/S45cron" "/etc/init.d/S65cloudupdate"; do
	if [ -f $file ]; then
		rm -f $file
	fi
done

rm -f /usr/lib/libcrypto.so.\*
rm -f /usr/lib/libssl.so.\*

if [ ${ROOTFS_VERSION_NEW} -gt ${ROOTFS_VERSION_OLD} ]; then

	log "Creating new Devices for Package 'rootfs' Version ${ROOTFS_VERSION_NEW}." "rootfs"

	# update ld.so.cache
	/sbin/ldconfig

	# fix the rights of /dev/null and /dev/zero
	chmod 0666 /dev/null
	chmod 0666 /dev/zero

	# disable ttyS0, if this is a 6400 card
	bftype=$(cat /sys/class/beronet/gateway/channels)
	if [ "${bftype}" = "64" ] && [ -c /dev/ttyS0 ]; then
		mv /dev/ttyS0 /dev/ttyS0_off
	fi

	# create bfpga-device
	if [ ! -c /dev/bfpga ] ; then
		log "Creating Device-Node '/dev/bfpga'." "rootfs"
		mknod /dev/bfpga c 254 0
	fi

	# create analog-devices
	if [ ! -c /dev/analog23 ] ; then
		for i in $(seq 0 23) ; do
			log "Creating Device-Node '/dev/analog${i}'." "rootfs"
			mknod /dev/analog$i c 253 $i
		done
	fi

	# create gsm-devices and set their ownership
	if [ ! -c /dev/gsm5 ]; then
		for i in $(seq 0 5); do
			log "Creating Device-Node '/dev/gsm${i}'." "rootfs"
			mknod /dev/gsm${i} c 252 ${i}
		done
	fi
	chown -R admin:admin /dev/gsm*

	# create cas-devices
	cas_dev_i=0
	for cas_i in $(seq 0 5); do
		dirname=/dev/cas${cas_i}
		if [ -d ${dirname} ]; then
			continue
		fi

		mkdir -p ${dirname}

		for cas_nam_i in $(seq 1 30); do
			log "Creating Device-Node '${dirname}/${cas_nam_i}'." "rootfs"
			mknod ${dirname}/${cas_nam_i} c 251 ${cas_dev_i}
			let cas_dev_i="${cas_dev_i}+1"
		done
	done

	# disable curl for php7:
	#### since php -v can lead to endless process, we check the sqlite2 binaries
	if [ ! -f /usr/bin/sqlite ]; then
		sed -i 's/extension/;extension/g' /etc/php.ini
	fi 

	# write and set new Version
	mount -o remount,rw /
	echo -e "TYPE=rootfs\nROOTFS=${ROOTFS_VERSION_NEW}" > /VERSION
	${BEROCONF} set root root-version ${ROOTFS_VERSION_NEW}
	mount -o remount,ro /
fi

## unmounting mtd5 space
mount -oremount,ro /

exit 0
