#!/bin/bash

if [ ${UID} -ne 0 ] ; then
	echo "Error, run again as root" 1>&2
	exit 1
fi

BASEDIR="$(readlink -f $0)"
[ -n "${BASEDIR}" ] && BASEDIR=$(dirname "${BASEDIR}")
if [ ! -d "${BASEDIR}" ] ; then
	echo "Error, directory containing the script not found." 1>&2
	exit 2
fi

ORIGIN_TAR="$1"
ROOTFS_IMG='linaro-rootfs.img'
[ -n "${ORIGIN_TAR}" ] && ORIGIN_TAR=$(readlink -f "${ORIGIN_TAR}")
if [ ! -f "${ORIGIN_TAR}" ] ; then
	echo "Error, original rootfs.tar not specified." 1>&2
	exit 3
fi

# goto base directory containing the script
cd "${BASEDIR}" || exit 4

# mandatory modifications
copy_addon() {
	local mandir='../addon'
	cp -f -v -r '--preserve=mode,timestamps' -P ${mandir}/* ./
	[ $? -ne 0 ] && return 1

	chmod 700 ./root/.ssh ./etc/ssh
	chmod 600 ./root/.ssh/authorized_keys ./etc/ssh/sshd_config ./root/.ssh/id_rsa*
	chown -R 1000:1000 ./home/linaro
	chown root:root ./usr/local/forceroot
	chmod 755 ./usr/local/forceroot ; chmod u+s ./usr/local/forceroot

	# remove /etc/init.d/rockchip.sh, refer to /usr/bin/lnxall-inst.sh
	rm -rf -v ./etc/init.d/rockchip.sh ./etc/xdg/autostart/blueman.desktop

	sed -e '/PARTLABEL=oem/d' -e '/PARTLABEL=userdata/d' -i ./etc/fstab
	return 0
}

copy_webapp() {
	local app='../resource/smu.tar.gz'
	local target_dir='opt/elect_resources/resources/app/'
	if [ -f "${app}" ] ; then
		mkdir -p $target_dir
		tar -zxf ${app} -C $target_dir
		[ $? -ne 0 ] && return 1
	fi
	#
	local update_pkg=$(find ../resource/ -type f -name smu_ver*.zip | head -n 1)
	if [ -z "$update_pkg" ]; then
		echo "update_pkg is null"
	else
		echo "unzip $update_pkg"
		unzip -o $update_pkg -d $target_dir
		chmod a+x opt/elect_resources/resources/app/bin/packapp
	fi
	return $?
}

copy_app() {
	local fwup='../resource/LNXALL_APP_RK3568_fwupgrade.elf'
	if [ -f "${fwup}" ] ; then
		mv -f -v "${fwup}" ./root/
		[ $? -ne 0 ] && return 1
	fi
	return 0
}

gen_rootfs() {
	rm -rf binary ; sync
	if [ -e "${ROOTFS_IMG}" ] ; then
		echo "Error, cannot continue due to existing ${ROOTFS_IMG}" 1>&2
		return 1
	fi

	tar -Jxf "${ORIGIN_TAR}"
	[ $? -ne 0 ] && return 2
	cd ./binary || return 3

	copy_addon && copy_app && copy_webapp
	[ $? -ne 0 ] && return 4

	# determine rootfs size in MB
	local imgsize=$(($(du -sh -m . 2>/dev/null | cut -f1) + 300))
	cd .. # go back upper directory

	# create rootfs image
	dd if=/dev/zero "of=${ROOTFS_IMG}" bs=1M count=0 seek=${imgsize}
	mkfs.ext4 -d ./binary ${ROOTFS_IMG}
	return $?
}

gen_rootfs ; exit $?
