#!/bin/sh
source /lib/functions.sh
source /etc/prplconfig
if [ -f "/lib/functions/ext4vol.sh" ]; then
    source /lib/functions/ext4vol.sh
fi
if [ -f "/lib/functions/ubivol.sh" ]; then
    source /lib/functions/ubivol.sh
fi

umount_perm(){
    umount /perm
    if [ -n "$CONFIG_SAH_BOARD_CONFIGURATOR_EXT4_SUPPORT_SINGLE_PARTITION" ]; then
        umount /data
    fi
}

do_mount_overlay_ram() {
    # check if we need to mount overlay in RAM
    if [ -n "$CONFIG_SAH_BOARD_CONFIGURATOR_ALLOW_OVERLAYFS" ]; then
        # check the type of filesystem and mount the /perm partition accordingly
        if [ -n "$CONFIG_SAH_BOARD_CONFIGURATOR_EXT4_PHYSICAL_MOUNT_PERM" ]; then
            mount_ext4 "/perm" "$CONFIG_SAH_BOARD_CONFIGURATOR_EXT4_PHYSICAL_MOUNT_PERM"
        elif [ -n "$CONFIG_SAH_BOARD_CONFIGURATOR_EXT4_SUPPORT_SINGLE_PARTITION" ]; then
            mount_ext4_single_data_partition "${CONFIG_SAH_BOARD_CONFIGURATOR_EXT4_SUPPORT_SINGLE_PARTITION_NAME}"
            mount_ext4_single_partition "perm"
        elif [ -n "$CONFIG_SAH_BOARD_CONFIGURATOR_EXT4_SUPPORT" ]; then
            mount_ext4 "/perm" "perm_data"
        elif [ -n "$CONFIG_SAH_BOARD_CONFIGURATOR_UBI_SUPPORT" ]; then
            mount_ubifs "/perm" ${CONFIG_SAH_BOARD_CONFIGURATOR_PERM_DATA_SIZE_MB} ${CONFIG_SAH_BOARD_CONFIGURATOR_PERM_DATA_VOL_ID} "perm_data"
        else
            echo "couldn't mount /perm"
            return 1
        fi

        if [ -f "/perm/.overlay" ]; then
            echo "Not mounting overlay in RAM since /perm/.overlay exists."
            # unmount the /perm partition (overlay will be put over /)
            umount_perm
            return 0
        fi
        # unmount the /perm partition (overlay will be put over /)
        umount_perm
    fi

    # mount overlay in ram
    echo "Mounting overlay in RAM"
    ramoverlay

    # Overwrite /sbin/mount_root in the overlayFS to avoid the overlay being mounted on a flash partition
    echo '#!/bin/sh' > /sbin/mount_root
}

boot_hook_add preinit_main do_mount_overlay_ram
