#!/usr/bin/env bash

# -------------------------------------------------------------------- 
# Synopsis: uqjau initial installer
#   (bootstrap, standalone script, no dependencies)
# -------------------------------------------------------------------- 
# Usage: $ourname [-s TAR_GZ_PACKAGES_PATHNAME]  [-i INSTALL_DIR] [-r REV]
# -------------------------------------------------------------------- 
#
# Options:
#   -s TAR_GZ_PACKAGES_PATHNAME
#           Default: ./pkgs.tar.gz, then /tmp/pkgs.tar.gz
#   -i INSTALL_DIR
#           currently must be a full pathname (TBD), but dir will be created if required
#           Default: $(mktemp -d /tmp/$ourname.XXXXXXXXX)
#   -r REV
#           As in $_29r/package/REV.
#           default is "cur"       
# -------------------------------------------------------------------- 

# --------------------------------------------------------------------
# $Source: /usr/local/7Rq/package/cur/main-2010.11.26/sbin/RCS/setup._m4,v $
# $Date: 2012/01/26 02:37:39 $ GMT    $Revision: 1.17 $
# --------------------------------------------------------------------

# ====================================================================
# Copyright (c) 2010, 2011, 2012 Tom Rodman <Rodman.T.S@gmail.com>
# --------------------------------------------------------------------

# == Software License ==
# This file is part of uqjau.
#
# uqjau 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.
#
# uqjau is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with uqjau.  If not, see <http://www.gnu.org/licenses/>.
# ---

array_from_STDIN_for_eval()
{ 
  # This instance is an internal function, not used outside of $ourname
  local arrayname=$1
  local line i=0
  while read -r line;do
    # TBD: meta quote contents of $line /could contain a " for ex/
    echo $arrayname\[$i\]=\""$line"\"
    let i++ || :
  done
}

ourname=${0##*/}

set -eu

trap '
  last_stat=$?
  last_command=${BASH_COMMAND-"OOPs BASH_COMMAND not defined"}
  echo last_command: $BASH_COMMAND, last stat: $last_stat
' ERR

# ==================================================
# parse commandline switches
# ==================================================
opt_true=1 OPT_s="" OPT_i="" OPT_r=""
while getopts r:s:i: opt_char
do
   # save info in an "OPT_*" env var.
   test "$opt_char" != \? && eval OPT_${opt_char}="\"\${OPTARG:-$opt_true}\"" || false
done
shift $(( $OPTIND -1 ))
unset opt_true opt_char

arc=${OPT_s:-/tmp/pkgs.tar.gz}

[[ -n $OPT_s ]] &&
{ arc=$OPT_s; } ||
{
  [[ -s ./pkgs.tar.gz ]] &&
  { arc=./pkgs.tar.gz; } ||
  { [[ -s /tmp/pkgs.tar.gz ]] &&
    { arc=/tmp/pkgs.tar.gz; } ||
    { echo "$ourname:ERROR: pls provide: \[-s TAR_GZ_PACKAGES_PATHNAME]" >&2
      exit 1
    }
  }
}

arc_ls=$(ls -log $arc|sed -e 's~^~  ~')

source_tar_file_info=$(
  echo CWD: $PWD
  echo $ourname: install archive:
  echo "$arc_ls"
  echo
)

echo "$source_tar_file_info"
sleep 2

# -------------------------------------------------------------------- 
# untar to $TMPDIR to expose individual package tarfiles
# -------------------------------------------------------------------- 
TMPDIR=$(mktemp -d /tmp/${ourname}.XXXXXXXXXX)
(set -x;tar -C $TMPDIR -zxf $arc)

# -------------------------------------------------------------------- 
# setup final package dir
# -------------------------------------------------------------------- 
install_root=${OPT_i:-$(mktemp -d /tmp/$ourname.XXXXXXXXX)}
install_root=$(set -e;mkdir -p $install_root;cd $install_root; pwd -P)
  # convert to physical pathname

rev=${OPT_r:-cur}

pk_top=$install_root/package/$rev
(set -x;mkdir -p $pk_top)
echo

# -------------------------------------------------------------------- 
# collect package names in 'package' bash array 
# -------------------------------------------------------------------- 
cd $TMPDIR
mk_package_array=$(find . -maxdepth 1 -name "*.tar.gz" | array_from_STDIN_for_eval package )
cd - >/dev/null

eval "$mk_package_array"

# ==================================================================== 
# untar all the packages themselves to final $pk_top dir
# ==================================================================== 
echo $ourname: untarring packages below $pk_top
for pk in $TMPDIR/*.tar.gz
do
  if untar_a_pkg=$(exec 2>&1;set -x;tar -C $pk_top -zxpf $pk )
  then :
  else
    retval=$?
    echo "$untar_a_pkg"|sed -e 's~^    ~~'
    sed -e 's~^    ~~' <<____eohd  >&2
    tar returned: $retval

    Hint(s) that may or may not be valid: 
    
      tar may be refusing to delete a preexisting file or symbolic
      link, with the same name of the pathname it is restoring,
      where the pathname to be restored is of a mismatching type
      ( example: restoring symbolic link foobar, but a dir by
      that name pre-exists )  In this case you need to rename or
      deleting the preexisting pathname.

____eohd
    exit $retval
  fi
done
echo

# ==================================================================== 
# configure packages
#   - add symb link w/shorter name to package dir
#   - add in symb links for tools w/in package to commands, scommands,..
# ==================================================================== 
packages_configure=$(mktemp /tmp/$ourname.packages_configure.XXXXXXXX)

exec 4>&2
  # save fd for STDERR
{
  # -------------------------------------------------------------------- 
  # install main package only
  # -------------------------------------------------------------------- 
  set -x;cd $pk_top/main-[0-9][0-9][0-9][0-9]*;set +x
  
  export main_install_warnings=$(mktemp /tmp/$ourname.XXXXXXXX)
    # crude, but this filename needed by child of ./install ( or deeper? )
  
  ./_install -b
  # TBD validate symbolic link
  
  # -------------------------------------------------------------------- 
  # install (or configure) each package
  # -------------------------------------------------------------------- 
  
  fatal_error=0
  echo -n "$ourname@$(date +%H:%M), longest step/pls wait, setting up symbolic links below [$pk_top] for each package.." >&4
  for p in "${package[@]}";do
    if (
      set -e
      #echo HI to STDERR >&4
      dir_bn=${p#./}
      dir_bn=${dir_bn%.tar.gz}
    
      [[ $dir_bn == main-* ]] && continue

      set -x; cd $pk_top/$dir_bn ;set +x
    
      ./install -b
      :
    )
    then :
    else
      fatal_error=1
      break;
    fi
  done 
  { echo DONE ;echo; } >&4 ; sleep 1.2
} > $packages_configure 2>&1

if [[ $fatal_error = 1 ]] ;then
  cat $packages_configure >&2
  exit 1
fi
### install done

(
set -ex
: post install work
cd $pk_top/main/etc
PATH="$PATH:$install_root/commands/$rev" make dirdefs.perl
)

# cleanup
rm -f $TMPDIR/*gz $packages_configure $main_install_warnings
rmdir $TMPDIR

echo
echo $ourname: complete
echo

echo "$source_tar_file_info"
echo
echo $ourname: installs done in: $pk_top

[[ -s ${main_install_warnings:-} ]] &&
{ echo;cat ${main_install_warnings} ; } || :
