#!/bin/bash
#
# Simple script that echoes the command line, it's environment variables and
# the user details it is running under
#
# Optional configuration environment variables:
#
# - echo_success - success probability (0-100). When set specifies the probability of returning success.
#                  Default = 80
#
# - echo_run_min - minimum runtime in seconds (0-3600).
#                  Default = 2
#
# - echo_run_max - maximum runtime in seconds (0-3600).
#                  Default = 5
#
# for full details see: https://beyondcron.com/docs/bc-agent/echo.html
#
# Note: if echo_run_max is less than echo_run_min, then the runtime will be echo_run_min
#
# Copyright 2023 BeyondCron Pty Ltd and related entities / All rights reserved.

main() {

  initCommands

  echo Command
  echo -------
  echo "$*"
  echo

  echo User details
  echo ------------
  echo 'user:' `${cmd_id} -un`
  echo 'group:' `${cmd_id} -gn`
  echo 'umask:' `umask`
  echo 'dir:' `pwd`
  echo

  echo Environment
  echo -----------
  vars=`${cmd_env} | ${cmd_sort}`
  while read -r var
  do
    echo "${var/=/ = }"
  done <<< "${vars}"
  echo

  read line
  if [ -n "${line}" ]; then
    echo Output
    echo ------
    echo "${line}"
    echo
  fi

  echo Input
  echo -----
  IFS=''
  while read -r line
  do
    echo "${line}"
  done

  runtimeWait
  randomlyFail

  exit 0
}

initCommands() {
  if [ -x /usr/bin/env ]; then
    cmd_env=/usr/bin/env
  else
    cmd_env=/bin/env
  fi

  if [ -x /usr/bin/id ]; then
    cmd_id=/usr/bin/id
  else
    cmd_id=/bin/id
  fi

  if [ -x /usr/bin/sort ]; then
    cmd_sort=/usr/bin/sort
  else
    cmd_sort=/bin/sort
  fi

  cmd_sleep=/bin/sleep
}

runtimeWait() {
  if isNumber 'echo_run_min' ; then
    if [ ${echo_run_min} -gt 3600 ]; then
      echo_run_min=3600
    fi
  else
    echo_run_min=2
  fi

  if isNumber 'echo_run_max' ; then
      if [ ${echo_run_max} -gt 3600 ]; then
          echo_run_max=3600
      fi
  else
    echo_run_max=5
  fi

  i=$(( ${echo_run_max} - ${echo_run_min} ))
  if [ ${i} -gt 0 ]; then
    ${cmd_sleep} $(( ${echo_run_min} + (${RANDOM} % ${i}) ))
  elif [ ${echo_run_min} -gt 0 ]; then
    ${cmd_sleep} ${echo_run_min}
  fi
}

randomlyFail() {
  if [ -z "${echo_success}" ]; then
    echo_success=80
  fi

  if isNumber 'echo_success' ; then
    if [ ${echo_success} -le 100 -a \
      $(( ${RANDOM} % 100 )) -ge ${echo_success} ]; then
      exit 1
    fi
  fi
}

isNumber() {
  value=${!1}
  re='^[0-9]+$'
  if ! [[ ${value} =~ $re ]]; then
    if [ -n "${value}" ]; then
      echo "${1} (${value}) is not a number" >&2
    fi
    return 1
  fi
  return 0
}

main $*

# end