#!/bin/bash

# Copyright (C) 2013 Ole Tange and Free Software Foundation, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This script downloads the latest version of GNU Parallel and
# installs it.
#
# It first tries to install it globally.
# If that fails, it does a personal installation.
# If that fails, it does copies to $HOME/bin

if [ "$(id -u)" == "0" ]; then
  cd /usr/src || exit 1
else
  cd || exit 1
fi

LATEST=$(wget -qO- http://ftpmirror.gnu.org/parallel | grep -o parallel-20...... | sort | tail -n1)
test -d $LATEST/src/ || wget http://ftpmirror.gnu.org/parallel/parallel-latest.tar.bz2 -O - | bzip2 -dc | tar xvf -
#test -d $LATEST/src/ || wget http://ftp.gnu.org/gnu/parallel/parallel-latest.tar.bz2 -O - | bzip2 -dc | tar xvf -
cd $LATEST || exit 2

if ./configure && make && make install; then
  echo GNU Parallel v${LATEST#*-} installed globally
  exit 0
else
  if ./configure --prefix=$HOME && make && make install; then
    echo GNU Parallel v${LATEST#*-} installed in $HOME/bin
  else
    mkdir -p $HOME/bin/
    chmod 755 src/*
    cp src/parallel src/sem src/sql src/niceload $HOME/bin
    echo GNU Parallel v${LATEST#*-} copied to $HOME/bin
  fi
fi

# is $HOME/bin already in $PATH?
echo $PATH | grep $HOME/bin >/dev/null || {
  echo 'PATH=$PATH:$HOME/bin' >> $HOME/.bashrc
  echo 'setenv PATH ${PATH}:${HOME}/bin' >> $HOME/.cshrc
}

