#!/usr/bin/ash
# Thanks to Patryk Jaworski's and his mkinitcpio-squashfs package for the help.

mount_handler_unsqaushtmpfs () {

    local device device_mp squashrootpath unsquashtmp_mp

    # Device existence test
    device="${squashimgpath%%:*}"
    if [ ! -e "$device" ]; then
        _device="$device"
        device=$(blkid -lt "$device" -o device)
    fi
    if [ ! "$device" ]; then
        err  "Device not detected: "$_device"."
        echo "device= define correctly to continue."
        launch_interactive_shell
        msg  "Trying to continue..."
    fi

    # Device mount
    device_mp=/mnt/${device##*/}
    mkdir -p "$device_mp"
    if ! mount "$device" "$device_mp"; then
        err  "Mount error: "$device" to "$device_mp"."
        launch_interactive_shell
        msg  "Trying to continue..."
    fi

    # SquashFS image existence test
    squashrootpath="$device_mp"/"${squashimgpath##*:}"
    if [ ! -f "$squashrootpath" ]; then
        err  "SquashFS image not found: "$path"."
        echo "squashimgpath= define correctly to continue."
        launch_interactive_shell
        msg  "Trying to continue..."
    fi

    # Tmpfs create
    if [ ! "$squashtmpsize" ]; then
        err  "squashtmpsize= not specified."
        echo "Specify squashtmpsize= in bytes"
        launch_interactive_shell
        msg  "Trying to continue..."
    fi
    unsquashtmp_mp=/mnt/unsquashtmp
    mkdir -p "$unsquashtmp_mp"
    if ! mount -t tmpfs tmpfs "$unsquashtmp_mp" \
         -o rw,size="$squashtmpsize",relatime
    then
        err  "Tmpfs creation failed."
        echo "It may be possible the system does not have enough memory."
        launch_interactive_shell
        msg  "Trying to continue..."
    fi   

    # SquashFS image decompress
    if ! unsquashfs -d "$unsquashtmp_mp" -f "$squashrootpath"; then
        err  "SquashFS decompression failed."
        echo "Does squashtmpsize= specify enough memory?"
        launch_interactive_shell
        msg  "Trying to continue..."
    fi

}

run_hook() {

    mount_handler=mount_handler_unsqaushtmpfs

}

# vim: ai ts=4 sw=4 ft=sh:
