#!/bin/bash

Option="$1"
InstallForUser="$2"

#{ parse arguments
if [ "$Option" == "REPLACE" ]; then
  Mode_Replace="1"
else
   if [ "$Option" == "REUSE" ]; then
    Mode_Reuse="1"
  else
    ERROR="ERROR: Missing argument MODE (got '$Option')"
  fi
fi
if [ "$InstallForUser" != "" ]; then
  if [ ! -d "/home/$InstallForUser" ]; then
    ERROR="ERROR: Homedir of user '$InstallForUser' (/home/$InstallForUser) not found!"
  else
    cd /home/$InstallForUser
    HOME=`pwd`
    USER="$InstallForUser"
  fi
else
  cd
fi
#}
if [ "$Option" == "" ] || [ "$ERROR" != "" ]; then #{
  cat <<END_OF_HELP
$0 <MODE> [<USERNAME>]

The ToolChain - Automatic updater script.
This script can download and update to newest release of a 32-bit development toolchain
for microcontrollers named The ToolChain (http://thetoolchain.com)

The ToolChain has been originally developed by Gregor Rebel 2011 - 2015


<MODE>   operating mode
         == REPLACE: will remove existing toolchain of same version before installation 
                     All install scripts will be run and all sources are recompiled.
         == REUSE:   will move existing toolchain of same version aside and reuse binary data.
                     Reusing an existing toolchain can speed up the installation process as
                     sources must not be recompiled (e.g. OpenOCD takes long to compile).
                     If you have issues after installation, a replacement installation is recommended.

<USERNAME>  if given, The ToolChain will be installed into /home/USERNAME for given user
            Note: Installing for another user requires to run this script as root!

Examples:
  $0 REUSE
  sudo $0 REPLACE gordon

$ERROR

END_OF_HELP
  exit 10
fi #}
function intoDir() { # 
  Dir="$1"

  if [ ! -d "$Dir" ]; then
    mkdir "$Dir"
  fi
  if [ ! -d "$Dir" ]; then
    echo "$0 - ERROR: Cannot create folder '`pwd`/$Dir' !"
    exit 10
  fi
  cd "$Dir"  
} #

chmod +x $0
Archive="TheToolChain_current.tar.bz"

InstallScript=`perl -e "my \\\$P=rindex('$0', '/'); print substr('$0', \\\$P+1);"` # script is everything after last / character
NewInstallScript="${InstallScript}_new"
rm -f "$NewInstallScript"
wget http://thetoolchain.com/$InstallScript -O "$NewInstallScript"
if [ "$NewInstallScript" -nt "$InstallScript" ]; then
  echo "using newer install script.."
  mv "$InstallScript" "${InstallScript}.old"
  mv "$NewInstallScript" "$InstallScript"
  bash ./$InstallScript $@
  exit 0
fi

intoDir Source
intoDir TheToolChain.install
sudo rm -Rf *

NewInstall=`ls TheToolChain_* -d | grep -v tar.bz`
if [ "$NewInstall" != "" ] && [ -d "../$NewInstall" ]; then #{ previous installation exists: move it aside or delete it
  if [ -d "../${NewInstall}.old" ]; then #{ remove old old version 
    sudo rm -Rf "../${NewInstall}.old"
  fi #}
  if [ $Mode_Replace == "1" ]; then # remove old version
    echo "removing existing toolchain: ${NewInstall}"
    sudo rm -Rf "../${NewInstall}"
  else                             # move old version aside
    echo "reusing existing toolchain: ${NewInstall}"
    mv -v "../${NewInstall}" "../${NewInstall}.old"
  fi
fi #}
rm -f ../TheToolChain

echo "downloading current version into `pwd`"
find ./ -maxdepth 1 -name "TheToolChain_*" -exec sudo rm -Rf {} \; # remove remains of previous, failed install run
wget -c http://thetoolchain.com/$Archive
tar xjf $Archive

if [ "$InstallForUser" != "" ]; then
  chown -R $InstallForUser: *
fi

cd TheToolChain/InstallData/
./installAll.sh BASIC "$InstallForUser"

if [ -e OK.AllInstalls ]; then
  echo "Installation successfull: TheToolChain rev`cat ../Version`"
else
  PWD=`pwd`
  cat <<END_OF_INFO
$0 - ERROR: Error occured during installation

Further steps:
cd "$PWD"
./installAll.sh BASIC

If installation fails again:
- check log files ($PWD/Logs/)
- run failed install script manually (./install_XXX.sh)
- move failed install script aside (mv install_XXX.sh ../) and retry

END_OF_INFO
  exit 20
fi

cd $HOME/Source
NotMoved=`ls 2>/dev/null TheToolChain.install/$NewInstall`
if [ "$NotMoved" != "" ]; then
  sudo rm -Rf $NewInstall
  rm -Rf TheToolChain $Archive
  sudo find TheToolChain.install/ -maxdepth 1 -mindepth 1 -exec mv {} . \;
fi
if [ -d TheToolChain.install ]; then
  rmdir TheToolChain.install
fi

cd $HOME/Source/TheToolChain/InstallData/
OptionalScripts=`ls optional/install_*`
cat <<END_OF_HELP

$0: Basic installation finished successfully.

You may now install optional software by running their install scripts manually:

cd $HOME/Source/TheToolChain/InstallData/
$OptionalScripts

Have fun!

END_OF_HELP