#!/bin/sh
set -e
#
# Simple installer for stda
# Author: Dimitar Ivanov
#
VER=1.2
PROG=stda
[ x$BIN_DIR = x ] && BIN_DIR=/usr/local/bin
[ x$MAN_DIR = x ] && MAN_DIR=/usr/local/man/man1
SRC_DIR=src
UIDGID=0:0
BIN_FILES=`cd $SRC_DIR && ls -1 * |grep -v \.1`
MAN_FILES=`cd $SRC_DIR && ls -1 * |grep \.1` || true

### Functions
#
Usage () {
    cat << !

Usage: $0 [OPTION]... < install | uninstall >

Options:
   -b, --bin-dir=<DIR>      - Directory where to install the executables;
                              Default is $BIN_DIR.
   -m, --man-dir=<DIR>      - Directory where to install the manual pages;
                              Default is $MAN_DIR.
   -o, --owner=<USER:GROUP> - Specify ownership for the installed files;
                              This argument is ignored if you are not root.
                              Default is $UIDGID.
   -q, --quiet              - Don't ask any questions and run quietly
   -h, --help               - Display this help

!
}

iamwho () {
   > /tmp/.$$
   ls -al /tmp/.$$ |tr -s ' ' |cut -f3 -d' '
   rm -f /tmp/.$$
}

### Process options and arguments
#
set -- `echo $* |tr '=' ' '`
[ -z "$1" ] && set -- -h

while [ $# -gt 0 ]
do
case $1 in
     -i|install)
         ALLED=installed
         CMD='install -d $1 && cp -f $2 $1'
         CHMOD=chmod
         CHOWN=chown
         ;;
     -u|uninstall)
         ALLED=uninstalled
         CMD='[ -f $1/$2 ] && rm $1/$2 || echo "No such file: $1/$2"'
         CHMOD=:
         CHOWN=:
         ;;
     -q|--quiet)
         QUIET=yes
         ;;
     -b|--bin-dir)
         BIN_DIR=$2
         shift
         ;;
     -m|--man-dir)
         MAN_DIR=$2
         shift
         ;;
     -o|--owner)
         UIDGID=$2
         shift
         ;;
      *) Usage
         exit
         ;;
esac
shift
done


### Do install/uninstall
#
[ $ALLED ] || { Usage ; exit ; }

[ $QUIET ] || {
  echo ""
  echo "              --- '$PROG' installer ---"
  echo ""
  echo "Following files will be $ALLED:"
  echo =========
  [ -n "$BIN_FILES" ] && \
    echo $BIN_FILES |tr ' ' '\n' |while read f; do echo $BIN_DIR/$f; done
  [ -n "$MAN_FILES" ] && \
    echo $MAN_FILES |tr ' ' '\n' |while read f; do echo $MAN_DIR/$f; done
  echo ""
  echo "Go ahead [y/N]"
  read y
  if [ y$y != yy ]; then echo "Exiting now .." ; exit ; fi
}

   # If not root, don't try to change ownership
me=`iamwho`
[ $me != root ] && CHOWN=:

cd $SRC_DIR || exit 1

   # Install/Uninstall some file
for file in $BIN_FILES $MAN_FILES
do
    if [ `expr $file : .*.1` -eq 0 ]; then
         set -- $BIN_DIR $file 755
    else
         set -- $MAN_DIR $file 644
    fi
       # copy or remove
    eval $CMD
       # change mode (skipped on uninstall)
    $CHMOD $3 $1/$2
       # change owner (skipped on uninstall)
    $CHOWN $UIDGID $1/$2
done

cd ..

[ $QUIET ] || {
  echo ""
  echo "'$PROG' $ALLED successfully"
  echo ""
}

exit 0
