#!/usr/bin/bash

#script to run configuration scripts

VERSION="(NCID) 1.18"

########################
# Function definitions #
########################

usage() {
cat <<EOF

Usage: $prog [-h] [-V] [name [option] [option] [...]]

Options: -h = show this help
         -V = display version

Arguments: none        - List available setup scripts and support files
           name        - The name part of the script name: ncid-<name>-setup
           name option - If option is needed by ncid-<name>-setup

EOF

exit 1
}


list_files() {

   # pass 1 = 'setup' or 'support' for the kind of files to show in the current directory
   #      2 = heading
   # returns code is integer count of files displayed

   found=0
   show_kind=$1
   show_heading="$2"

   shopt -s nullglob
   indent=5
 
   for i in *; do

       show_filename=$i
       if [ "${i:0:5}" = "ncid-" ] && [ "${i:(-6)}" = "-setup" ]; then
          this_kind=setup
          show_filename="$(echo "$show_filename" | sed 's/^ncid\-//;s/\-setup$//')"
       else
          this_kind=support
       fi

       [ $this_kind != $show_kind ] && continue

       ((found++))

       if [ $found -eq 1 ]; then
          echo
          echo "$show_heading"
          echo
       fi

       printf "%*s%s\n" $indent "" "$show_filename"

   done

   return $found

}

###############################
# End of function definitions #
###############################

prog=`basename $0 .sh`

SetupDir=/usr/share/ncid/setup

# Options on command line
while getopts :hV opt ; do
    case $opt in
        h) usage;;
        V) echo "$prog $VERSION"; exit 0;;
        :) echo "Option -$OPTARG requires an argument."; usage;;
        *) echo "Invalid option: -$OPTARG"; usage;;
    esac
done
shift $((OPTIND-1)) # skip over command line args (if any)

[ -d $SetupDir ] || \
{
    echo "$SetupDir: No such directory."
    exit 0;
}

cd $SetupDir # in case setup directory contains helper files for $script

[ "$#" -ge 1 ] || \
{

    list_files setup "List of available setup scripts in $SetupDir:"
    rc=$?
    if [ $rc -eq 0 ]; then
       echo "$SetupDir: No setup scripts are available."    
       exit 0
    fi

    list_files support "List of available support files in $SetupDir:"
    rc=$? # don't care

    exit 0

}

name=$1; shift

script=$SetupDir/ncid-$name-setup

[ -f $script ] || \
{
    echo "Setup script not found: $script"
    exit 1
}

export main_prog=$prog

$script $*
