#!/bin/sh
set -eu

fail() {
	logger -t one-kvm-shared "$*"
	echo "one-kvm-shared: $*" >&2
	exit 1
}

# Use the mounted boot partition, as ophub does. Never scan unrelated disks.
boot_device="$(df -P /boot | awk 'NR == 2 { print $1 }')"
boot_device="$(readlink -f "$boot_device")" || fail 'Cannot resolve boot device'
[ "$(blkid -s TYPE -o value "$boot_device")" = vfat ] || fail '/boot is not mounted from FAT boot partition'
case "$boot_device" in
	/dev/mmcblk*p1|/dev/nvme*n*p1) prefix="${boot_device%1}" ;;
	/dev/sd[a-z]1|/dev/hd[a-z]1|/dev/vd[a-z]1) prefix="${boot_device%1}" ;;
	*) fail "Unsupported boot partition: $boot_device" ;;
esac
root_device="$(df -P / | awk 'NR == 2 { print $1 }')"
root_device="$(readlink -f "$root_device")" || fail 'Cannot resolve root device'
if [ "$root_device" = /dev/root ]; then
	root_spec="$(tr ' ' '\n' </proc/cmdline | sed -n 's/^root=//p' | head -n 1)"
	case "$root_spec" in
		PARTUUID=*|UUID=*) root_device="$(blkid -t "$root_spec" -o device)" ;;
		*) fail 'Cannot identify /dev/root from kernel boot arguments' ;;
	esac
fi
case "$root_device" in "${prefix}2"|"${prefix}3") ;; *) fail 'Boot and root partitions are on different disks' ;; esac

if [ -f /root/.todo_rootfs_resize ]; then
	# This call completes synchronously before the application services start.
	/usr/sbin/openwrt-tf || fail 'ROOTFS2/SHARED initialization failed'
fi

shared_device="${prefix}4"
[ -b "$shared_device" ] || fail 'SHARED partition 4 is missing'
[ "$(blkid -s TYPE -o value "$shared_device")" = ext4 ] || fail 'SHARED must be ext4'
mountpoint="/mnt/${shared_device##*/}"
mkdir -p "$mountpoint"
if ! awk -v device="$shared_device" -v path="$mountpoint" '
	$1 == device && $2 == path && $3 == "ext4" && $4 ~ /(^|,)rw(,|$)/ { found=1 }
	END { exit !found }
' /proc/mounts; then
	mount -t ext4 -o noatime "$shared_device" "$mountpoint" || fail 'Cannot mount SHARED'
fi
# Never cover a nonempty directory with a link or silently change a mounted path.
if [ -L /mnt/shared ]; then
	rm /mnt/shared
elif [ -e /mnt/shared ]; then
	rmdir /mnt/shared || fail '/mnt/shared exists and is not an empty directory'
fi
ln -s "$mountpoint" /mnt/shared
/usr/libexec/one-kvm-shared-ready || fail 'SHARED is not writable'
mkdir -p /mnt/shared/one-kvm /mnt/shared/docker
chmod 700 /mnt/shared/one-kvm

# Persist the actual device UUID; retain the standard ophub mount location.
shared_uuid="$(blkid -s UUID -o value "$shared_device")"
[ -n "$shared_uuid" ] || fail 'SHARED UUID is missing'
uci set fstab.shared=mount
uci set "fstab.shared.target=$mountpoint"
uci set "fstab.shared.uuid=$shared_uuid"
uci set fstab.shared.fstype=ext4
uci set fstab.shared.options=noatime
uci set fstab.shared.enabled=1
uci commit fstab
