#!/bin/bash

function add_overlay_lower_dir() {
    local overlay=${1}
    if [[ ! -d "${overlay}" ]]; then
        local msg="ERROR: ${overlay} is not a directory"
        echo "${msg}"
        echo "${msg}" | log
        return 1
    fi
    local file="/tmp/overlay-lowers"
    if [ -f "${file}" ]; then
        #append the new overlay to the beginning of the file
        sed -i "1s?^?${overlay}:?" "${file}"
    else
        echo -n "${overlay}" > "${file}"
    fi
}

function log() {
    tag=${1:-"lwr-boot"}
    if [ "$#" -gt 1 ]; then
        echo "${tag}: ${*:2}" >> /dev/kmsg
    else
        while read -r line; do
            echo "${tag}: ${line}" >> /dev/kmsg
        done
    fi
}

function fail(){
    echo -e "$1" | log
    bash
}

# mount /proc
mount -t proc proc /proc
mount -t sysfs sysfs /sys

# create a writable fs. It's needed to create our mountpoints
mkdir -p /tmp

mount -t tmpfs inittemp /tmp || fail "ERROR: could not create a temporary filesystem to mount the base filesystems for overlayfs"
TMP_MNT=/tmp/mnt
mkdir -p $TMP_MNT

#already mounted from ramfs
UID_DIR=/mnt/uid
STORAGE_DIR=/mnt/storage
SYSTEM_DIR=/mnt/system
VARIANT_OVERLAY="/mnt/variant-rootfs"

mount -o ro,remount "${UID_DIR}"
#TÁK: ${SYSTEM_DIR} will be ro remounted by resizefs to avoid readonly resize error


# shellcheck disable=SC1091
source "/usr/lib/lwr/lwr-boot-functions.sh"

lwr_boot_mount_variant_overlay "$(lwr_boot_get_variant_dir_from_uid ${UID_DIR})" "${SYSTEM_DIR}/rootfs" "${VARIANT_OVERLAY}" || fail "ERROR: could not mount /mnt/variant-rootfs" | log

add_overlay_lower_dir "${VARIANT_OVERLAY}"
# Functions can be used from "/etc/lwr-boot.d" scripts
export -f add_overlay_lower_dir
export -f log
export -f fail
for file in $(find ${VARIANT_OVERLAY}/etc/lwr-boot.d -maxdepth 1 -type f 2>/dev/null | sort); do
    echo "Run ${file}" | log
    ( "${file}" || echo "Failed to run" ) | log "$(basename "${file}")"
done

NEW_ROOT="${TMP_MNT}/newroot"
LOWER_DIRS="$(cat /tmp/overlay-lowers)"
lwr_boot_mount_rw_overlay "${NEW_ROOT}" "${STORAGE_DIR}" "${LOWER_DIRS}" || fail "ERROR: could not mount overlayFS" | log

lwr_boot_move_mountpoints "/mnt/" "${NEW_ROOT}" | log

mkdir -p "${NEW_ROOT}/old-root"

cd "${NEW_ROOT}" || fail "ERROR: could not cd to ${NEW_ROOT}"

echo "pivot_root ${NEW_ROOT} ${NEW_ROOT}/old-root" | log
/sbin/pivot_root "${NEW_ROOT}" "${NEW_ROOT}/old-root" || fail "pivot_root failed"
echo "chroot to $(pwd)"

# shellcheck disable=SC2093
exec chroot . /bin/sh  <<"EOT"
mkdir -p /tmp && mount --move /old-root/tmp /tmp && rm -rf /tmp/mnt;
umount /old-root/{dev,proc,sys} && umount /old-root && rm -r /old-root;
mount --bind /mnt/uid /uid; 
exec /sbin/init
EOT

# shellcheck disable=SC2181
if [ $? -ne 0 ]; then
    fail "ERROR: chroot"
fi

