#!/bin/sh

set -e

mountpoints="system data vendor"

syslabels="APP system"
datalabels="UDA userdata"

diskpath=/dev/disk/by-partlabel

mountopts="noatime,nodiratime,errors=remount-ro"
romountopts="ro,${mountopts}"
bindmountopts="ro,bind"

tmpfile=$(mktemp /tmp/fstab.XXX)

cleanup()
{
    case $? in
		0)
			mv $tmpfile /etc/fstab
			chmod 644 /etc/fstab
			echo "manual" >/etc/init/lxc-android-fstab.override
			echo "success"
			;;
		*)
			rm -rf $tmpfile
			echo "failed"
			;;
	esac
}
trap cleanup EXIT INT QUIT ILL KILL SEGV TERM

# logging
log=/var/log/lxc-android-fstab.log
exec 3>&1 4>&2 >$log 2>&1

# we require android partlabels
[ -e "$diskpath" ] || exit 1

# prepare working file
cp /etc/fstab $tmpfile
echo >>$tmpfile

for mount in $mountpoints; do
	path=$diskpath
	fs="ext4"
	part=""

	# make sure the mountpoint exists at all
	[ -e "/$mount" ] || mkdir -p /$mount

	# different options per mountpioint
	case $mount in
		system)
			labels=$syslabels
			options=$romountopts
			;;
		data)
			labels=$datalabels
			options=$mountopts
			;;
		vendor)
			labels=$mount
			options=$bindmountopts
			path="/system"
			fs="auto"
			;;
	esac

	# check if there is an fstab entry already
	for name in $labels; do
		if grep -q -P "^$path/$name(\t| )+/$mount(\t| )+" /etc/fstab; then
			part=$name
		fi
	done

	# create an entry if there was none
	if [ -z "$part" ] ; then
		for name in $labels; do
			if [ -e "$path/$name" ] || [ "$name" = "vendor" ]; then
				echo "# added by lxc-android-fstab for /$mount" >>$tmpfile
				echo "$path/$name	/$mount	$fs	$options	0	0" >>$tmpfile
			fi
		done
	fi
done
