#!/bin/bash

FURIOS_PERSIST="/dev/disk/by-partlabel/vendor_boot_a"

if [ -f "/usr/lib/furios/device/furios-persist-partition" ]; then
    source /usr/lib/furios/device/furios-persist-partition
else
    echo "furios-persist is not supported"
    exit 0
fi

if [ ! -e "${FURIOS_PERSIST}" ]; then
    echo "Partition ${FURIOS_PERSIST} not found."
    exit 0
fi

filesystem=$(blkid -o value -s TYPE "${FURIOS_PERSIST}")
if [ ! "${filesystem}" == "ext4" ]; then
    echo "wiping partition ${FURIOS_PERSIST} to ext4 to use as furios-persist"
    FULLPATH=$(readlink -f "${FURIOS_PERSIST}")
    mkfs.ext4 -F "${FULLPATH}"

    mkdir -p /var/lib/furios-persist
    mount "${FURIOS_PERSIST}" /var/lib/furios-persist
else
    if ! mountpoint -q /var/lib/furios-persist; then
        mkdir -p /var/lib/furios-persist
        mount "${FURIOS_PERSIST}" /var/lib/furios-persist

        # TODO: this should not be needed. for some reason ramdisk sometimes does not move it out of the way
        # perhaps a `sync` or `sleep 1` in ramdisk could fix it?
        if [ -f "/var/lib/furios-persist/bootman/next-boot" ]; then
            mv /var/lib/furios-persist/bootman/next-boot /var/lib/furios-persist/bootman/old-boot
        fi
    fi
fi

exit 0
