#!/bin/bash
# SATNOGS_PRE_OBSERVATION_SCRIPT
# satnogs-pre {{ID}} {{FREQ}} {{TLE}} {{TIMESTAMP}} {{BAUD}} {{SCRIPT_NAME}}

#
# This script reads all scripts from ./satnogs-pre.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-pre "$@"
}

PRE_DIR="./satnogs-pre.d"

log "Starting pre-obs-script."
if [[ -d "$PRE_DIR" ]]; then
  for script in "$PRE_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 $PRE_DIR does not exist. Exiting."
  exit 1
fi
