#!/bin/bash

if grep -q -e '^overlay.*/filesystem.squashfs' /proc/mounts; then
	# Live CD boot
	exit 2

elif grep -q 'upperdir=/live/persistence/' /proc/mounts && egrep -q 'overlay / overlay ' /proc/mounts; then
	# VyOS-style union boot (forked live-boot)
	boot_device=`grep -o 'upperdir=/live/persistence/[^/]*/boot' /proc/mounts | cut -d / -f 4`
	persist_path="/lib/live/mount/persistence/$boot_device"

	echo $persist_path
	exit 0

elif grep -q 'upperdir=/run/live/persistence/' /proc/mounts && egrep -q 'overlay / overlay ' /proc/mounts; then
	# Stock Debian live-boot persistence (GreenOS install-to-disk)
	# The overlay upper dir is on the persistence partition:
	#   upperdir=/run/live/persistence/<device>-root/...
	# The partition root is mounted at /run/live/persistence/<device>-root
	persist_mount=$(grep -o 'upperdir=/run/live/persistence/[^/]*' /proc/mounts | head -1 | sed 's/upperdir=//')
	if [ -n "$persist_mount" ] && [ -d "$persist_mount/boot" ]; then
		echo "$persist_mount"
		exit 0
	fi

	# Fallback: find any mount under /run/live/persistence/ with a boot/ dir
	for d in /run/live/persistence/*/; do
		if [ -d "${d}boot" ]; then
			echo "${d%/}"
			exit 0
		fi
	done

	exit 1
else
	# old style boot
	exit 1
fi
