#!/bin/sh

set -e

usage() {
  cat <<'EOF'
Usage:

  admin-remote-connections --accept-incoming
                           --is-incoming-accepted
                           --reject-incoming
                           --show-enable-time

  Give one of "--accept-incoming", "--is-incoming-accepted",
  "--reject-incoming" or "--show-enable-time" options.
  If connections are accepted, "--is-incoming-accepted"
  prints "yes" to standard output, and "no" if those are rejected.

  This tool does nothing on hosts which are not personally administered.
EOF
}

action=$1

set -u

# This tool is not currently effective on hosts which are not personally
# administered, so return error if this script is called in that case.
personally_administered=$(puavo-conf puavo.admin.personally_administered)

if [ "$personally_administered" != 'true' ]; then
  echo 'This host is not personally administered, I can do nothing' >&2
  exit 1
fi

config_file_path="/var/lib/puavo-desktop/shared/admin-remote-connections.conf"

case "$action" in
  --accept-incoming)
    if [ -e "$config_file_path" ]; then
      touch "$config_file_path"
    else
      touch "$config_file_path"
      chmod 666 "$config_file_path"
    fi
    ;;
  -h|--help)
    usage
    exit 0
    ;;
  --is-incoming-accepted)
    if [ -e "$config_file_path" ]; then
      echo yes
    else
      echo no
    fi
    ;;
  --reject-incoming)
    rm -f "$config_file_path"
    ;;
  --show-enable-time)
    stat -c %Y "$config_file_path" 2>/dev/null \
      || echo 'not enabled'
    ;;
  *)
    usage >&2
    exit 1
    ;;
esac
