#!/bin/bash
# Copyright (c) 2008 Alon Swartz <alon@turnkeylinux.org> - all rights reserved
### BEGIN INIT INFO
# Provides:          di-live
# Required-Start:    $syslog
# Required-Stop:
# Should-Start:      $local_fs
# Should-Stop:       halt reboot
# Default-Start:     S
# Default-Stop:      0 6
# Short-Description: TurnKey Linux installer (di-live)
# Description:       On 'start' will launch di-live, if set as boot option
#                    On 'stop' will eject disc and prompt user, if post install
### END INIT INFO

NAME=di-live
EJECT_FLAG=/tmp/.di-live-finalize

set -e
. /lib/lsb/init-functions

cache_path() {
    path="$1"

    if [ -d "$path" ]; then
        find "$path" -type f | xargs cat > /dev/null 2>&1
    elif [ -f "$path" ]; then
        if [ -x "$path" ]; then
            if file "$path" | grep -q 'dynamically linked'; then
                for lib in $(ldd "$path" | awk '{ print $3 }'); do
                    cache_path "$lib"
                done
            fi
        fi
        cat "$path" >/dev/null 2>&1
    fi
}


case "$1" in
  start)
        grep -qs di-live /proc/cmdline || exit 0

        log_begin_msg "Starting $NAME"
        FGCONSOLE=$(fgconsole)
        FGVT=$FGCONSOLE openvt -f -c 8 -s -w -- di-live
        chvt $FGCONSOLE
        log_action_end_msg $?
        ;;

  stop)
        grep -qs boot=casper /proc/cmdline || exit 0
        [ -e $EJECT_FLAG ] || exit 0
        which file >/dev/null || exit 0
        which eject >/dev/null || exit 0

        for path in $(which stty bash true halt reboot sysctl systemctl systemd) /etc/bash.bashrc /etc/rc?.d /lib/systemd /etc/default; do
            cache_path "$path"
        done

        eject -p -m /cdrom >/dev/null 2>&1
        exit 0
        ;;

  restart|reload|force-reload)
        echo "Error: argument '$1' not supported" >&2
        exit 3
        ;;

  *)
    N=/etc/init.d/$NAME
    echo "Usage: $N {start|stop}" >&2
    exit 1
  ;;
esac

exit 0
