#!/bin/sh
### BEGIN INIT INFO
# Provides:     pidp8i
# Required-Start:   $syslog
# Required-Stop:    $syslog
# Default-Start:    2 3 4 5
# Default-Stop:     0 6
# Short-Description:PiDP-8/I simulator
# Description:      The PiDP-8/I simulator is a modified version of
#                   the SimH PDP-8 simulator for the PiDP-8/I front
#                   panel project for the Raspberry Pi.
### END INIT INFO

########################################################################
# Init script for Oscar Vermeulen's PiDP-8/I emulator front panel.  
#
# Original author: Mark G Thomas <mark@misty.com> 2015-05-09
#
# Copyright © 2015 Mark G Thomas
# Copyright © 2017 Warren Young
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS LISTED ABOVE BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
# OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Except as contained in this notice, the names of the authors above
# shall not be used in advertising or otherwise to promote the sale,
# use or other dealings in this Software without prior written
# authorization from those authors.
########################################################################

PATH=/sbin:/usr/sbin:/bin:/usr/bin
umask 022
. /lib/lsb/init-functions

prefix="@ABSPREFIX@"
sim="$prefix/bin/pidp8i-sim"
scanswitch="$prefix/libexec/scanswitch"

# Requires screen utility for detached pidp8i console functionality.
test -x /usr/bin/screen || ( echo "screen not found" && exit 0 )

# Also check for other needed binaries
test -x $scanswitch || ( echo "$scanswitch not found" && exit 0 )
test -x $sim || ( echo "$sim not found" && exit 0 )

# Check if pidp8i is already runnning under screen.
#
is_running() {
    procs=`screenu -ls pidp8i | egrep '[0-9]+\.pidp8i' | wc -l`
    test $procs -gt 0 && return 0 || return 1
}

# Wrapper around screen(1) to drop privileges and pass given args
screenu() {
    if [ "$USER" = "@INSTUSR@" ]
    then
        /usr/bin/screen $*
    else
        su -c "/usr/bin/screen $*" @INSTUSR@
    fi
}

do_start() {
    if is_running ; then
        echo "PiDP-8/I is already running, not starting again." >&2
        exit 0
    fi

    # Regenerate SSH host keys if this is the first run on a fresh image
    if [ ! -f /etc/ssh/ssh_host_ecdsa_key -a -x /usr/sbin/dpkg-reconfigure ]
    then
        log_daemon_msg "Regenerating SSH host keys..." "pidp8i"
        /usr/sbin/dpkg-reconfigure openssh-server
    fi

    $scanswitch >/dev/null 2>&1
    script=$?
    if [ $script -eq 8 ]; then
        echo "PiDP-8/I STOP switch detected, aborting." >&2
        exit 0
    elif [ $script -lt 8 ]; then
        bscript="@BOOTDIR@/""$script"".script"
        echo "Booting from $bscript..."
    elif [ $script -eq 127 ]; then
        echo "PiDP-8/I panel not present.  Booting from 0.script..."
        bscript="@BOOTDIR@/0.script"
    else
        echo "Bad return value $script from $scanswitch!"
        exit 1
    fi

    # We want SIMH to have a sensible working directory: somewhere the
    # user can write files and which makes sense when giving SIMH
    # commands involving file paths.  This default is chosen because it
    # satisfies both criteria, plus it makes tools/mkos8 happy.
    # If you change the default here, change that script as well.
    cd "$prefix/share/media"

    log_daemon_msg "Starting PiDP-8/I simulator" "pidp8i"
    screenu -dmS pidp8i "$sim" $bscript
    status=$?
    log_end_msg $status
    return $status
}

do_stop() {
    if ! is_running ; then
        echo "PiDP-8/I is already stopped." >&2
        status=1
    else
        log_daemon_msg "Stopping PiDP-8/I simulator" "pidp8i"
	    screenu -S pidp8i -X quit ; sleep 1 ; pkill -f pidp8i-sim
        status=$?
        log_end_msg $status
    fi
    return $status
}

case "$1" in
  start)
    do_start
    ;;

  stop)
    do_stop
    ;;

  restart)
    do_stop
    do_start
    ;;

  status)
    if screenu -ls pidp8i | egrep -q '[0-9]+\.pidp8i'
    then
        echo "The PiDP-8/I simulator is running."
    else
        echo "The PiDP-8/I simulator is STOPPED."
    fi
    ;;

  *)
    log_action_msg "Usage: /etc/init.d/pidp8i {start|stop|restart|status}" || true
    exit 1
esac

exit 0
