#!/bin/bash

test -n "${OS_VERSION}" || source /etc/init.d/base

mount_fs() {
    msg_begin "Mounting filesystems"
    /bin/mount -T /etc/fstab.disk -a &&
    /bin/mount -T /etc/fstab.extra -a &&
    if [[ -r /data/etc/fstab.user ]]; then /bin/mount -T /data/etc/fstab.user -a; fi

    test $? == 0 && msg_done || msg_fail
}

mount_overlay() {
    modprobe overlay &>/dev/null
    grep -qw overlay /proc/filesystems || return

    msg_begin "Mounting overlay filesystems"
    grep -oE 'lowerdir=[^,]+' /etc/fstab.overlay | cut -d '=' -f 2 | xargs -r mkdir -p
    grep -oE 'upperdir=[^,]+' /etc/fstab.overlay | cut -d '=' -f 2 | xargs -r mkdir -p
    grep -oE 'workdir=[^ ]+' /etc/fstab.overlay | cut -d '=' -f 2 | xargs -r mkdir -p
    /bin/mount -T /etc/fstab.overlay -a
    test $? == 0 && msg_done || msg_fail
}

remount_rw() {
    msg_begin "Remounting boot partition read-write"
    mount -o remount,rw /boot
    test $? == 0 && msg_done || msg_fail

    msg_begin "Remounting root partition read-write"
    mount -o remount,rw /
    test $? == 0 && msg_done || msg_fail
}

mk_tty_login() {
    test -z "${OS_TTY_LOGIN}" && OS_TTY_LOGIN=tty1
    ln -sf /dev/${OS_TTY_LOGIN} /dev/ttylogin
}

case "$1" in
    start)
        mount_fs
        mount_overlay

        # we need to source conf again, now that /data is available
        source /etc/init.d/os_conf
        test "${OS_DEBUG}" == "true" && remount_rw
        mk_tty_login
        ;;

    stop)
        true
        ;;

    *)
        echo "Usage: $0 {start}"
        exit 1
esac

exit $?

