#!/sbin/openrc-run
#
# Warpgate bastion.
#
# Config, log and data directory are all derived from $RC_SVCNAME: symlinking
# this script under a second name runs a second, independent instance with its
# own /etc/conf.d file and nothing else to edit.

name="Warpgate"
description="SSH, HTTPS, RDP and database bastion"

: ${cfgfile:="/etc/$RC_SVCNAME.yaml"}
: ${datadir:="/var/lib/$RC_SVCNAME"}
: ${logfile:="/var/log/$RC_SVCNAME.log"}
: ${command_user:="$RC_SVCNAME:$RC_SVCNAME"}
  
command="/usr/bin/warpgate"
command_args="--config $cfgfile run"
  
supervisor="supervise-daemon"
pidfile="/run/supervise-$RC_SVCNAME.pid"
output_log="$logfile"
error_log="$logfile"
  
# Retry forever rather than giving up after N attempts: an unreachable database
# or a port still held by the old process are transient, and a bastion that
# stopped trying at 03:00 is discovered at 09:00 by someone locked out.
respawn_delay=5
respawn_max=0

# An ambient capability instead of running as root. Warpgate listens on 2222 and
# 8888 out of the box, but the point of a bastion is that people reach it on 22
# and 443. The leading "^" raises the capability in the ambient set as well as
# the inheritable one, which is what lets an unprivileged process actually use
# it after the privilege drop.
: ${capabilities:="^cap_net_bind_service"}
    
depend() {
  need net
  after firewall
}
   
start_pre() {
  # Say what to run rather than letting warpgate fail on a file that is not
  # there: setup asks for an admin password, so the package cannot create it.
  [ -f "$cfgfile" ] || {
    eerror "$cfgfile does not exist. Create it with:"
    eerror "  $command --config $cfgfile setup"
    return 1
  }
  # setup is run by hand as root and leaves the config owned by root, which the
  # service user cannot read. Hand it over without touching the mode: warpgate
  # writes it 0600 on purpose and checks that on startup.
  checkpath -f -o "$command_user" "$cfgfile"
  checkpath -d -m 0750 -o "$command_user" "$datadir"
  checkpath -f -m 0640 -o "$command_user" "$logfile"
  # checkpath fixes the directory but not what is inside it. setup is run by
  # hand as root, so the database it leaves behind belongs to root and the
  # service cannot open it. Test the contents -- the directory itself was just
  # adopted by checkpath above -- and only walk the tree when something is
  # actually owned by someone else.
  [ -n "$(find "$datadir" ! -user "${command_user%%:*}" -print -quit)" ] &&
    chown -R "$command_user" "$datadir"
  # Fail here on a config that will not parse, so a bad edit aborts the start
  # and -- on a restart -- leaves the running process alone.
  #
  # --skip-securing-files because this runs as root: without it warpgate would
  # "fix" the ownership of the config and database to root, and the service
  # user would no longer be able to read them.
  "$command" --config "$cfgfile" --skip-securing-files check
}