#! /bin/sh -
#
# A mouse configuration tool for gpm(8)
#
# Copyright (c) 2018-2020 Matias Fonzo, <selk@dragora.org>.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Exit immediately on any error
set -e

PROGRAM="${0##*/}"
TMPDIR="${TMPDIR:-$HOME}"
TMPFILE="${TMPDIR}/.${PROGRAM}.${RANDOM-0}$$"
LOCKFILE=/var/lock/dragora-mouse.lockfile

chkstatus_or_exit()
{
    status=$?

    # Clean up temporary files
    rm -f -- "$TMPFILE" "$LOCKFILE"

    if test $status -ne 0
    then
        printf '%s\n' "" "Return status = $status" 1>&2
        exit 2;
    fi

    unset status
}

# Sanity checks

if test ! -d "$TMPDIR"
then
    echo "${PROGRAM}: \`${TMPDIR}' is not a qualified temporary directory" 1>&2
    exit 1;
fi
if test ! -w "$TMPDIR"
then
    echo "${PROGRAM}: \`${TMPDIR}' is not a writable temporary directory" 1>&2
    exit 1;
fi

trap 'chkstatus_or_exit' EXIT HUP INT QUIT ABRT TERM

umask 077;	# Remove access for all but user.

# Unfortunately, gpm(8) is limited to the superuser;
# we set a lock to allow only one instance of the script.

if ( set -C ; echo ": $PROGRAM - locked" > $LOCKFILE ) 2> /dev/null
then
    true
else
    if test -e "$LOCKFILE"
    then
        echo "Only one instance of \`${PROGRAM}' is allowed." 1>&2
        exit 1;
    else
        echo "${PROGRAM}: \`${LOCKFILE}' lock failed." 1>&2
        exit 2;
    fi
fi

dialog --colors \
 --backtitle "\\Zb${PROGRAM} - Mouse Configuration" \
 --title "MAIN MENU" --menu \
"Welcome to \\Z3${PROGRAM}\\Zn!\\n\
    A configuration tool for the mouse selection.\\n\\n\
The following list is ordered by mouse type and brief description.\\n\
\\Zbp\\Zns2 is the most common model for laptops.  Otherwise, you can\\n\
select the \\Zbu\\Znsb model from the list below.\\n\\n\
Select a mouse type:" 20 71 6 \
"ps2"        "Common protocol for PS2 mice"                  \
"usb"        "Common protocol for USB mice"                  \
"bare"       "Microsoft compatible, 2 buttons"               \
"exps2"      "IntelliMouse Explorer, 3 buttons"              \
"imps2"      "Microsoft Intellimouse, 2 or 3 buttons"        \
"js"         "Mouse emulation with a Joystick"               \
"logi"       "Logitech devices"                              \
"logim"      "Logitech into Mouse-Systems compatible"        \
"mman"       "The MouseMan and similar devices"              \
"ms"         "Microsoft-compatible, 3 buttons"               \
"ms3"        "Microsoft Intellimouse, 3 buttons"             \
"msc"        "Mouse-Systems compatible, most 3-button mice"  \
"ncr"        "Ncr3125pen found on some laptops"              \
"netmouse"   "Genius NetMouse, 4 buttons"                    \
"pnp"        "Plug and Play mice, does not work with 'ms'"   \
"twid"       "Twidddler keyboard"                            \
"acecad"     "Acecad tablet, in absolute mode"               \
"genitizer"  "Genitizer tablet, in relative mode"            \
"wacom"      "Wacom Protocol IV tablets"                     \
"wp"         "Genius WizardPad tablet"                       \
2> "$TMPFILE"

# Read answer from 'TMPFILE'

echo "" >> "$TMPFILE";		# Append new line for reading.
IFS= read -r REPLY < "$TMPFILE" || exit 2;

# Check cases to determine the corresponding device name

case $REPLY in
ps2 | imps2 | exps2 | ncr | netmouse)
    DEVICE=psaux
    ;;
usb)
    REPLY=imps2
    DEVICE=input/mice
    ;;
acecad | bare | genitizer | logi* | twid | wacom | mman | ms* | pnp | wp)
    dialog --colors \
     --backtitle "\\Zb${PROGRAM} - Serial Port" \
     --title "MOUSE DEVICE" \
     --no-cancel --menu \
"The protocol \\Zb\\Z1${REPLY}\\Zn requires a serial port.\\n\\n\
Which device name would you like to use?" 13 52 4 \
      "ttyS0"  "Serial port 0, COM1 under DOS" \
      "ttyS1"  "Serial port 1, COM2 under DOS" \
      "ttyS2"  "Serial port 2, COM3 under DOS" \
      "ttyS3"  "Serial port 3, COM4 under DOS" \
    2> "$TMPFILE"
    echo "" >> "$TMPFILE";	# Append new line for reading.
    IFS= read -r DEVICE < "$TMPFILE" || exit 2;
    ;;
js)
    DEVICE=js0
    ;;
esac

# Temporary file is not needed anymore
rm -f -- "$TMPFILE"

umask 022;	# Remove write permission for group and other.

printf '%s\n' \
 "#! /bin/sh -"                                                      \
 "# Stop/Start gpm(8) the mouse server."                             \
 "# Automatically generated by dragora-mouse(8)."                    \
 ""                                                                  \
 "if pidof gpm > /dev/null"                                          \
 "then"                                                              \
 "    echo \"Stopping running gpm instance: gpm -k\""                \
 "    if ! gpm -k"                                                   \
 "    then"                                                          \
 "        echo \"Sending the TERM signal to gpm\""                   \
 "        killall -TERM gpm"                                         \
 "    fi"                                                            \
 "    sleep 1"                                                       \
 "fi"                                                                \
 ""                                                                  \
 "echo \"(Startup) Starting gpm: gpm -m /dev/${DEVICE} -t $REPLY\""  \
 "gpm -m /dev/${DEVICE} -t $REPLY"                                   \
 ""                                                                  \
 > /etc/rc.d/rc.gpm-sample
chmod 755 /etc/rc.d/rc.gpm-sample

dialog --colors \
 --backtitle "\\Zb${PROGRAM} - Startup File" \
 --title "RUN CONTROL" --yesno \
"A run control file could be created to load your settings\\n\
at boot time.  The file will be saved as \\Z1/etc/rc.d/rc.gpm\\Zn\\n\\n\
Would you like to load this file at boot time?" 8 63 && \
  mv -f -- /etc/rc.d/rc.gpm-sample /etc/rc.d/rc.gpm

dialog --colors \
 --backtitle "\\Zb${PROGRAM} - Mouse Session" \
 --title "MOUSE SESSION" --yesno \
"\\ZbGPM\\Zn is a cut and paste utility and mouse server for \
virtual consoles.  It is useful to avoid typing everything by \
hand\\Zb!\\Zn\\n\\n\
Would you like to run it now?" 9 58
echo ""
echo "Stopping any running gpm instance"
gpm -k 2> /dev/null || killall gpm 2> /dev/null || true;
sleep 1
echo ""
echo "Starting gpm: gpm -m /dev/${DEVICE} -t $REPLY"
gpm -m /dev/${DEVICE} -t $REPLY

