#!/bin/bash
# Start/stop terraform-http-backend.
#
### BEGIN INIT INFO
# Provides:          terraform-http-backend
# Required-Start:    $local_fs $remote_fs $network $syslog
# Required-Stop:     $local_fs $remote_fs $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Terraform HTTP state backend daemon
# Description:       Terraform HTTP state backend daemon
### END INIT INFO
# shellcheck disable=SC1091

NAME="terraform-http-backend"
DAEMON="/opt/sbin/$NAME"
DESC="Terraform HTTP state backend"

[[ -x "$DAEMON" ]] || exit 0

# shellcheck disable=SC2015
[[ -f /etc/default/terraform-http-backend ]] && . /etc/default/terraform-http-backend >/dev/null 2>&1 || {
  echo "$0: error reading: /etc/default/terraform-http-backend"
  exit 1
}
export TF_IP TF_PORT TF_STORAGE_DIR TF_AUTH_ENABLED TF_USERNAME TF_PASSWORD

. /lib/lsb/init-functions

case "$1" in
  start)
    log_daemon_msg "Starting $DESC" "$NAME"
    setpriv --keep-groups --reuid "${TF_USER:-root}" --regid "$(id -ng "${TF_USER:-root}")" -- "$DAEMON" >/dev/null 2>&1 &
    log_end_msg "$?"
    ;;
  stop)
    log_daemon_msg "Stopping $DESC" "$NAME"
    killall -TERM "$DAEMON"
    log_end_msg "$?"
    ;;
  restart|force-reload)
    "$0" stop
    sleep 1
    "$0" start
    ;;
  status)
    status_of_proc "$DAEMON" "$NAME" && exit 0 || exit "$?"
    ;;
  *)
    echo "Usage: $0 start|stop|restart|force-reload|status"
    exit 1
    ;;
esac

exit 0
