#!/bin/sh
# @description force the agent to create and send a new inventory
# @man This will trigger a new inventory creation and send it to the policy server.
# @man Even if the agent will do it regularly, it can be used to force the update
# @man after a modification on the node.
# @man This won't affect the node state, but only update server-side information.
# @man +
# @man *Options*:
# @man +
# @man *-i*: run the agent in information mode, prints basic information
# @man +
# @man *-v*: run the agent in verbose mode, prints detailed information
# @man +
# @man *-d*: run the agent in debug mode, prints low-level information
# @man +
# @man *-q*: run the agent in quiet mode (display only error messages)
# @man +
# @man *-w*: show full strings, never cut output
# @man +
# @man *-c*: run the agent without color output
# @man +
# @man *-T*: display timing information
# @man +
# @man *-r*: run the agent with raw output
# @man +
# @man *-R*: run the agent in completely unparsed mode, with no return code of 1 in case of error. A little faster.
# @man +
# @man *-f*: run the agent even if it is disabled

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

bootstrap_check

# We cannot start an inventory in bootstrap policies without https
if ! is_https_only && cmp -s "${RUDDER_VAR}/cfengine-community/inputs/failsafe.cf" "${RUDDER_DIR}/share/bootstrap-promises/failsafe.cf"
then
  >&2 echo "Agent is currently in bootstrap policies, cannot run an inventory. Please download initial policies from the server with command \"rudder agent update\" first. If problem persists, use \"rudder agent check\" for diagnostic"
  exit 1
fi

# Ignore disable-inventory flag
FORCE=0
OPTS=""
optmax=0
err=0
VERBOSE_INVENTORY="false"
# err=1 -> we have a parameter with an argument
# err=2 -> we have reached the end (or we have invalid parameters)
while [ ${err} -lt 2 ]
do
  getopts ":fv" opt # ':' -> ignore getopt errors
  res=$?
  [ ${OPTIND} -lt ${optmax} ] && break # OPTIND value has wrapped, we reached the end of parameters
  if [ ${res} -eq 0 ]
  then
    [ "${opt}" = "f" ] && FORCE=1
    if [ "${opt}" = "v" ]; then
      OPTS="-v ${OPTS}"
      VERBOSE_INVENTORY="true"
    fi
    err=0
  else
    err=$((err+1))
    OPTIND=$((OPTIND+1))
    optmax=${OPTIND} # to detect wrapping
  fi
done

if [ ${FORCE} -eq 0 ] && [ -e ${RUDDER_DIR}/etc/disable-inventory ]; then
  printf "${RED}error${NORMAL}: The inventory is currently disabled.\n"
  exit 1
fi

if is_https_only; then
  # if this file exists, then we have regular promises, then initial inventory has been already sent
  if [ -f /var/rudder/cfengine-community/inputs/rudder.json ]; then
    INITIAL_INVENTORY="false"
  else
    INITIAL_INVENTORY="true"
  fi
  do-inventory "${INITIAL_INVENTORY}" "${VERBOSE_INVENTORY}"
else
  # Add the class to force inventory if requested
  [ ${FORCE} -eq 1 ] && OPTS="-D ignore_disable_inventory"

  ${RUDDER_BIN} agent run -l -N -D force_inventory -b doInventory "$@" ${OPTS}
fi
