#!/bin/bash
# @description reload techniques
# @man This command will reload the technique library into memory from
# @man the filesystem and regenerate the policies if necessary.
# @man +
# @man *Options*:
# @man +
# @man *-i*: run the agent in information mode, displays all executed commands
# @man +
# @man *-c*: run the agent without color output

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

DISPLAY_COMMAND=false

while getopts "iIvdc" opt; do
  case $opt in
    i|I|v|d)
      DISPLAY_COMMAND=true
      ;;
    c)
      clear_colors
      ;;
  esac
done

# Make call to jetty directly and bypass apache conf so we are sure we have no problem to call reload techniques API
action="reload techniques from files"
curl_opt="--header @/var/rudder/run/api-token-header --request POST"
expected='{"action":"reloadTechniques","result":"success","data":{"techniques":"Started"}}'

# check if the API is available
api_result=$(rudder_api_call "/system/status" "GET" "" "${DISPLAY_COMMAND}" 2>/dev/null)
api_code=$?

if [ ${api_code} -eq 0 ]
then
  checked_api_call "http://127.0.0.1:8080/rudder/api/latest/system/reload/techniques" "reload techniques from files" "${DISPLAY_COMMAND}" "${expected}" "${curl_opt}"
else
  echo "Web interface is down - requested a technique reload at its restart"
  touch ${RUDDER_DIR}/etc/force_technique_reload
fi

