#!/bin/bash

# sourcing our current rc.conf requires this to be a bash script
. /usr/lib/rc/functions

mount_fs(){
    findmnt / --options ro &>/dev/null || mount -o remount,ro / || return 1
    return 0
}

# umount_fs(){
#     umount -r -a -t nosysfs,noproc,nodevtmpfs,notmpfs
# }

umount_fs() {
    findmnt -mrunRo TARGET,FSTYPE,OPTIONS / | {
        while read -r target fstype options; do
            # interpret the ascii chars, such as \x20 (space)
            printf -v target '%b' "$target"
            # match only targeted fstypes
            if [[ $1 && $1 != "$fstype" ]]; then
                continue
            fi

            # do not unmount API filesystems
            if [[ $target = /@(proc|sys|run|dev|dev/pts) ]]; then
                continue
            fi

            # avoid networked devices
            IFS=, read -ra opts <<< "$options"
            if in_array _netdev "${opts[@]}"; then
                continue
            fi

            mounts=("$target" "${mounts[@]}")
        done

        # There are differences between verbose and non-verbose method
        # because iterating the array is considerably slower than the
        # non-verbose method
        if (( ${#mounts[*]} )) && ck_verbose; then
            for ((i=0; i<${#mounts[*]}; i++)); do
                substat "Unmounting ${mounts[i]}"
                umount -r "${mounts[i]}" || return 1
            done
        elif (( ${#mounts[*]} )); then
            umount -r "${mounts[@]}" || return 1
        fi
        return 0
    }
}

case "$1" in
    start)
        stat_busy "Mounting filesystems"
        mount_fs || stat_die root
        add_daemon root
        stat_done root
        ;;
    stop)
        stat_busy "Unounting filesystems"
        umount_fs || stat_die root
        rm_daemon root
        stat_done root
        ;;
    *)
        echo "usage: $0 {start|stop}"
        exit 1
        ;;
esac
