#!/bin/bash

BASH="$(command -v bash)"
PYTHON="$(command -v python3)"

# Allowed script extensions
ALLOWED_SCRIPT_EXTENSIONS=("sh")

if [ -n "${PYTHON}" ]; then
  ALLOWED_SCRIPT_EXTENSIONS+=("py")
fi

run_script() {
  local path="$1"
  local extension="${path##*.}"

  if [ "$extension" = "py" ]; then
    python3 "$path"
  elif [ "$extension" = "sh" ]; then
    bash "$path"
  else
    echo "Unsupported script type: $path" >&2
    return 1
  fi
}

run_scripts() {
  local dir="$1"
  local output=""
  local item

  for item in $(ls -1 "$dir" | sort); do
    local item_path="$dir/$item"
    if [ -f "$item_path" ]; then
      local extension="${item##*.}"
      if [[ " ${ALLOWED_SCRIPT_EXTENSIONS[*]} " =~ " $extension " ]]; then
        output+=$(run_script "$item_path")
        output+=$'\n'
      fi
    fi
  done
  echo "$output"
}

generate_motd() {
  local source="${1:-/etc/motdgen.d}"
  local outfile="$2"
  local message

  message=$(run_scripts "$source")
  if [ -n "${outfile}" ]; then
    local outdir
    outdir=$(dirname "${outfile}")

    if [ ! -d "$outdir" ]; then
      mkdir -p "$outdir"
    fi
    echo "${message}" > "${outfile}"
    chmod 644 "${outfile}"
  else
    echo "${message}"
  fi
}

usage() {
echo -en "\nusage: motdgen [-h] [-s SOURCE] [-o DEST]

options:
  -h, --help            show this help message and exit

  -s SOURCE, --source SOURCE
                        Directory containing scripts to generate MOTD

  -o DEST, --output DEST
                        File to dump generated MOTD\n\n"

  exit 1
}

main() {
  local source="/etc/motdgen.d/"
  local dest=""

  while [[ "$#" -gt 0 ]]; do
    case "$1" in
      -s|--source)
        source="$2"
        shift 2
        ;;
      -o|--output)
        dest="$2"
        shift 2
        ;;
      *)
        usage
        ;;
    esac
  done

  generate_motd "$source" "$dest"
}

# Entry point
if [[ "${BASH_SOURCE[0]}" = "$0" ]]; then
  main "$@"
fi
