#!/usr/bin/env bash

# shellcheck shell=bash

me="service-commands"
mode=$(basename "$0")

if [ "${mode}" = "${me}" ] && [ -z "$*" ]; then
  here=$(dirname "$0")
  printf '%s\n' "Setting up handy service shortcuts in ${here} ... "
  cd "${here}" || return
  for op in {,u}s{re,rl,st,t,sp,p,ta}; do
    if ! [ -e "${op}" ]; then
      ln -s "${me}" "${op}"
      printf '%s\n' " ${op}"
    fi
  done
  echo
  exit 0
fi

user=
# shellcheck disable=SC2249
case "${mode}" in
  u*)
    user=--user
    mode="${mode#u}"
    ;;
esac

case "${mode}" in
  sre)
    op=restart
    ;;
  srl)
    op=reload
    ;;
  st | sst)
    op=start
    ;;
  sp | ssp)
    op=stop
    ;;
  sta)
    op=status
    ;;
  *)
    echo "$0: Unrecognised mode '${mode}'"
    exit 1
    ;;
esac

service="$1"
if [ -n "$1" ]; then
  shift
elif [ "${op}" != status ]; then
  echo >&2 "Missing service name; aborting"
  exit 1
fi
# shellcheck disable=SC2312
if [ "$(id -u)" != 0 ] && [ -z "${user}" ]; then
  # 'ave a go son
  sudo=sudo
else
  sudo=
fi

if command -v systemctl >/dev/null 2>&1; then
  case "${op}" in
    status)
      # For some moronic reason, systemctl --lines=N status doesn't
      # work properly.  I'm guessing it only shows lines since the
      # service was
      "${sudo}" systemctl -n 0 --no-pager "${user}" "${op}" "${service}" "$@"
      if [ -z "${user}" ]; then
        unit_option=-u
      else
        unit_option=--user-unit
      fi
      echo
      "${sudo}" journalctl -n 10 --no-pager "${user}" "${unit_option}" "${service}" "$@"
      ;;
    *)
      exec "${sudo}" systemctl "${user}" "${op}" "${service}" "$@"
      ;;
  esac
elif [ -x /sbin/service ]; then
  # legacy v1
  exec "${sudo}" /sbin/service "${service}" "${op}" "$@"
else
  # legacy v2
  exec "${sudo}" /etc/init.d/"${service}" "${op}" "$@"
fi
