#!/bin/bash

set -e
set -o errtrace
set -o pipefail
set -o nounset

true "$0: INFO: START"

# start-stop-daemon is in /usr/sbin, but the caller might not have /usr/sbin
# in its PATH variable, so we need to locate it ourselves.
ssd="$(command -v /usr/sbin/start-stop-daemon)"
pidfile="/run/user/$(id -u)/dist-virtual-keyboard.pid"

terminate_wvkbd() {
  "$ssd" --remove-pidfile --stop --quiet --retry=TERM/5/KILL/5 --pidfile "$pidfile" &>/dev/null || true
}

launch_wvkbd() {
  program="/usr/bin/wvkbd-mobintl"

  "$ssd" \
    --background \
    --make-pidfile \
    --pidfile "$pidfile" \
    --exec "$program" \
    --start
}

if (( $# > 0 )) && [ "$1" = '--terminate' ]; then
  terminate_wvkbd
  exit
fi

launch_wvkbd
