#!/bin/sh
#
# Simple installer for dish 
# Author: Dimitar Ivanov
#
set -e
VER=1.1.1

PROG=dish
DIST_FILES='
$BINDIR:dish:0755
$MANDIR:dish.1:0644
'
LINK_FILES='
$BINDIR:dicp:dish
'
BINDIR=/usr/local/bin
MANDIR=/usr/local/man/man1
SRCDIR=src
UIDGID=0:0

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

Usage: $0 [ -i | -u ] [ -b <bin-dir> ] [ -m <man-dir> ]

Options:
   -i              - Install program
   -u              - Uninstall program
   -b <bin-dir>    - Directory where to install the executable(s),
                     default is $BINDIR
   -m <man-dir>    - Directory where to install the manual page(s),
                     default is $MANDIR
   -o <user:group> - Specify ownership for the installed files. This argument
                     is ignored if you are not root. Default is $UIDGID
   -q              - Don't ask any questions and run quietly

!
}

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

### Process options and arguments
#
[ -z "$1" ] && set -- -h

while [ $# -gt 0 ]
do
case $1 in
     -i) ALLED=installed
         CMD='cp -f $2 $1'
         LINK='cd $1 && test ! -h $2 && ln -s $3 $2 || true'
         CHMOD=chmod
         CHOWN=chown
      ;;
     -u) ALLED=uninstalled
         CMD='rm -f $1/$2'
         LINK='cd $1 && rm -f $2'
         CHMOD=:
         CHOWN=:
      ;;
     -q) QUIET=yes
      ;;
     -b) BINDIR=$2
         shift
      ;;
     -m) MANDIR=$2
         shift
      ;;
     -o) 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 =========
  files=`echo "$DIST_FILES" "$LINK_FILES"`
  echo `eval echo $files` |tr ' ' '\n' |cut -d: -f1-2 |tr : /
  echo ""
  echo "Go ahead [y/N]"
  read y
  if [ y$y != yy ]; then echo "Exiting now .." ; exit ; fi
}

cd $SRCDIR || exit 1

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

   # cp/rm some file
for file in $DIST_FILES
do
    args=`echo $file |tr : ' '`
    set `eval echo $args`
       # copy or remove
    eval $CMD
       # change mode
    $CHMOD $3 $1/$2
       # change owner
    $CHOWN $UIDGID $1/$2
done

   # link/rm some files
for file in $LINK_FILES
do
    args=`echo $file |tr : ' '`
    set `eval echo $args`
    eval $LINK
done

cd ..

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

exit 0
