#!/bin/sh
set -eu

if [ ! "${1:-}" ]
then
    echo The command argument must be set to a target directory >&2
    echo It will create directories Bin, Includes, Libs and Documentation in that >&2
    echo Those can be renamed or moved after installation is complete >&2
    echo
    exit 1
fi
home=$1
if [ ! -d $home -o ! -w $home ]
then
    echo
    echo $home is not a writable directory
    echo
    exit 1
fi
exist=
for dir in $home/Bin $home/Includes $home/Libs $home/Documentation
do
    if [ -e $dir -a \( ! -d $dir -o ! -w $dir \) ]
    then
        echo
        echo $dir exists but is not a writable directory
        echo
        exit 1
    fi
    if [ -e $dir ]
    then
        exist="$exist $dir"
    fi
done
if [ "$exist" ]
then
    response=
    while [ ! "$response" ]
    do
        echo
        echo $exist already exist - do you want to continue?
        echo 'Please answer Yes or No: '
        read response
        if [ "`echo $response | tr '[a-z]' '[A-Z]'`" = NO ]
        then
            exit 1
        elif [ "`echo $response | tr '[a-z]' '[A-Z]'`" != YES ]
        then
            response=
        fi
    done
fi

echo
echo Unpacking the main materials into directory $home
echo

# Make the target directories and unpack the material

if [ ! -d $home/Bin ]
then
    mkdir $home/Bin
fi
cp -p run $home/Bin
if [ ! -d $home/Includes ]
then
    mkdir $home/Includes
fi
cp -p std_lib_facilities.h $home/Includes
if [ ! -d $home/Libs ]
then
    mkdir $home/Libs
fi
if [ ! -d $home/Documentation ]
then
    mkdir $home/Documentation
fi
if [ ! -d $home/Materials ]
then
    mkdir $home/Materials
fi
cat Materials.tar.gz | (cd $home; tar -xzf -)

echo The main materials have been unpacked
echo
echo Only $home/Bin and $home/Includes will include files at this stage
echo
