#!/bin/bash

# Offer to run a complex command from among those listed in specific files:
# ./.frequents and ~/.frequents.

# If an argument is present, it's taken as the line number to choose.
# Otherwise, user is presented with a consolidated list and prompted for
# line number of their choice.  In either case the choice is echoed and the
# command line is evalled.  (Using eval means the command line can contain
# multiple commands in a pipeline, sequence, and with backgrounded
# components.)  Lines that begin with a "#" hash mark are taken as
# commentary, presented for illumination but not included in choice count.

# klm  August, 2007

unset lines
unset comments

arg="$1"

NEWLINE="
"

read_from () {
  if [ -r "$1" ]; then
    exec 3< "$1"
    while read curline <&3; do
      if [ -n "$curline" ]; then
        case $curline in
          \#* ) if [ -n "${comments[${#lines[@]}]}" ]; then
                  comments[${#lines[@]}]+="${NEWLINE} $curline"
                else
                  comments[${#lines[@]}]="  $curline"
                fi;;
          * ) lines[${#lines[@]}]="$curline";;
        esac
      fi
    done
    exec 3<&-
  fi
}

if [ ! .frequents -ef ~/.frequents ]; then
  read_from .frequents
fi
read_from ~/.frequents

size=${#lines[@]}

if [ "$size" = 0 ]; then
  echo "no entries"
  exit
fi

which=""

if [ -n "$arg" ]; then
  which="$arg"
else
  echo
  incr=0
  for i in "${lines[@]}"; do
    if [ -n "${comments[$incr]}" ]; then
      echo "${comments[$incr]}"
    fi
    echo $((incr++)): $i
  done
  echo
  echo -n "execute command from line number[empty input to cancel]: "
  read which
fi

case "$which" in
  [0-9] | [0-9][0-9] | [0-9][0-9][0-9]) : ;;
  * ) echo cancelled
      exit;;
esac

if [ -z "${lines[$which]}" ]; then
   echo no match
   exit 1
else
   echo "$which: ${lines[$which]}"
   eval "${lines[$which]}"
fi

