#!/bin/sh
#
# ap - run a program with args read from standard input, prompted if from term
#    - read named arguments from stdin with prompts
#
# Usage: ap PROGRAM ARGNAME1 [ARGNAME2...]

if [ "$#" -eq 0 ]; then
  printf >&2 'ap: Need at least one argument (command name)\n'
  exit 2
fi

# get the command name and shift it off
cmd="$1"
shift

# iterate through the remaining args; it's legal for there to be none, but in
# that case the user may as well just have invoked the command directly
for arg; do

  # if this is the first iteration, clear params away
  # (we grabbed them in for statement)
  if [ -z "${reset}" ]; then
    set --
    reset=1
  fi

  # if stdin is a terminal, prompt with the name of the argument
  if [ -t 0 ]; then
    printf '%s: ' "${arg}"
  fi

  # note that a whitespace or even empty argument is allowed
  IFS= read -r val
  set -- "$@" "${val}"
done

# execute the command with the given parameters
exec "${cmd}" "$@"
