#!/bin/bash

usage()
{
    echo "
Usage: $0 [strip] all|progs|scripts|man|skel|doc|etc|docdoc [installdir]
"
    exit 1
}

[ -e tmp/ROOT ] || usage

. scripts/conversions

echo ROOT DIRECTORY: ${ROOT}

if [ "$1" == "strip" ] ; then
    STRIP=strip
    shift
fi

if [ "$2" != "" ] ; then
    INSTALLDIR=$2
else
    INSTALLDIR=${ROOT}
fi

try()
{
    echo $*
    $* || exit 1
}

progs()
{
    if [ "$STRIP" == "strip" ] ; then
        try strip tmp${BINDIR}/icmake tmp${BINDIR}/icmbuild \
                  tmp${LIBDIR}/*
    fi
    try mkdir -p $INSTALLDIR${BINDIR} $INSTALLDIR${LIBDIR}

    try cp tmp${BINDIR}/icmake tmp${BINDIR}/icmbuild \
                $INSTALLDIR${BINDIR}

    if [ -e $INSTALLDIR${LIBDIR}/icm-exec ] ; then
        try rm $INSTALLDIR${LIBDIR}/icm-exec 
    fi

    try cp -r tmp${LIBDIR}/* $INSTALLDIR${LIBDIR}
}

scripts()
{
    try mkdir -p $INSTALLDIR${BINDIR} $INSTALLDIR${LIBDIR} \
                 $INSTALLDIR${DOCDIR} 

                    # convert icmstart.sh to INSTALLDIR/usr/bin/icmstart
    try scripts/convert tmp/icmstart.sh $INSTALLDIR$BINDIR/icmstart
    try chmod +x $INSTALLDIR$BINDIR/icmstart

                    # convert icmbuild.in to icmbuild
    try scripts/convert tmp/icmbuild.in $INSTALLDIR$LIBDIR/icmbuild

                    # convert icmstart.in to docdir/icmstart.im
    try scripts/convert tmp/icmstart.in tmp/icmstart.im

    echo gzip -9cn tmp/icmstart.im \> $INSTALLDIR${DOCDIR}/icmstart.im.gz
    gzip -9cn tmp/icmstart.im > $INSTALLDIR${DOCDIR}/icmstart.im.gz || exit 1

                    # compile icmstart.im to $INSTALLDIR$LIBDIR//icmstart.bim
    try tmp${LIBDIR}/icm-pp tmp/icmstart.im tmp/icmstart.pim
    try tmp${LIBDIR}/icm-comp tmp/icmstart.pim \
                              $INSTALLDIR${LIBDIR}/icmstart.bim
}

into()
{
    try mkdir -p $INSTALLDIR/$1
    try cp -r tmp/$1/* $INSTALLDIR/$1
}

case $1 in
    (all)
        echo installing programs
        progs
        echo 

        echo installing scripts
        scripts
        echo

        echo installing man-pages in ${MANDIR}
        into ${MANDIR}
        echo

        echo installing skeleton files in ${SKELDIR}
        into ${SKELDIR}
        echo

        echo installing files to ${DOCDIR}
        into ${DOCDIR}
        echo

        #   echo installing 
        #   into ${DOCDOCDIR}
        #   echo

        echo installing /etc/icmake files
        into ${CONFDIR}
        echo
    ;;

    (progs)
        progs
    ;;

    (scripts)
        scripts
    ;;

    (man)
        into ${MANDIR}
    ;;

    (skel)
        into ${SKELDIR}
    ;;

    (doc)
        into ${DOCDIR}
    ;;

    (etc)
        into ${CONFDIR}
    ;;

    # (docdoc)
    #     into ${DOCDOCDIR}
    # ;;

    (*)
        usage
    ;;
esac
