#!/bin/sh
# @description start the relay service
# @man Start the relay service using the appropriate service manager.
# @man +
# @man *Options*:
# @man +
# @man *-q*: run the agent in quiet mode (display only error messages)
# @man +
# @man *-c*: run the agent without color output
# @man +
# @man *-p*: fix permissions of file used by relayd, and start it if not running


. "${BASEDIR}/../lib/common.sh"
. "${BASEDIR}/../lib/api_call.sh"

QUIET=false
DISPLAY_COMMAND=false

while getopts "qciIvdp" opt; do
  case $opt in
    i|I|v|d)
      DISPLAY_COMMAND=true
      ;;

    q)
      QUIET=true
      ;;
    c)
      clear_colors
      ;;
    p)
      if [ -f ${RUDDER_VAR}/lib/ssl/allnodescerts.pem ]; then chgrp rudder ${RUDDER_VAR}/lib/ssl/allnodescerts.pem; fi
      if [ -f ${RUDDER_VAR}/lib/ssl/allnodescerts.pem ] && type restorecon >/dev/null 2>&1; then restorecon ${RUDDER_VAR}/lib/ssl/allnodescerts.pem; fi
      if [ -f ${RUDDER_VAR}/lib/relay/nodeslist.json ]; then chown rudder-relayd ${RUDDER_VAR}/lib/relay/nodeslist.json; fi
      # Needed in case it was not running
      # Only do it in -p as it should not be done in the general case which is used by systemd to reload the service
      if ! systemctl is-active rudder-relayd >/dev/null; then
        systemctl start rudder-relayd
        exit 0
      fi
      ;;
  esac
done

checked_api_call "http://127.0.0.1:3030/rudder/relay-api/1/system/reload" "reload relayd configuration" "${DISPLAY_COMMAND}" '{"result":"success","action":"reloadConfiguration"}' "--request POST"

