#!/bin/bash
# SATNOGS_POST_OBSERVATION_SCRIPT
# satnogs-post {{ID}} {{FREQ}} {{TLE}} {{TIMESTAMP}} {{BAUD}} {{SCRIPT_NAME}}

#
# This script reads all scripts from ./satnogs-post.d and executes them in
# alphabetical order. For each script, you can configure custom cmd-line args
# by defining a SCRIPTNAME.arg file along it.
#
# Example:
#   10-home-rotator.sh
#   10-home-rotator.arg
#   20-upload-iq-dump.sh
#

log() {
    logger -t satnogs-post "$@"
}

POST_DIR="./satnogs-post.d"

log "Starting post-obs-script."
if [[ -d "$POST_DIR" ]]; then
  for script in "$POST_DIR"/*; do
    # Only process regular executable files (not *.args)
    if [[ -x "$script" && -f "$script" && ! "$script" =~ \.args$ ]]; then
      base="${script%.*}"   # Remove extension
      args_file="${script}.args"

      log "Running script $base..."
      if [[ -f "$args_file" ]]; then
        log "... with arguments from arg-file."
        # Read arguments from file, treat as one line of parameters
        mapfile -t custom_args < "$args_file"
        "$script" "${custom_args[@]}"
      else
        #Executing script with default args $@
        log "... with default args."
        "$script" "$@"
      fi
    fi
  done
else
  log "Directory $POST_DIR does not exist. Exiting."
  exit 1
fi
