#!/bin/bash

ME=`basename "$0"`
DEFAULT_PREFIX="$HOME/TrustBridge"
CFGPATH="${XDG_DATA_HOME:-$HOME/.local/share}/BSI/TrustBridge"
SYSCFGPATH="/etc/TrustBridge"
INSTCFGNAME="installation.cfg"

instcfg_file="${CFGPATH}/${INSTCFGNAME}"
declare -A instcfg
instcfg=(
  [TIMESTMP]=`date -u +%Y%m%d%H%M%S`
  [VERSION]='@PROJECT_VERSION@'
  [PREFIX]=''
)

version()
{
  cat <<EOF
TrustBridge ${instcfg[VERSION]} Installer

Copyright (C) 2014 by Bundesamt für Sicherheit in der Informationstechnik
Software engineering by Intevation GmbH

This is free software.  You may redistribute copies of it under the terms of
the GNU GPL (v>=2).   See LICENSE.txt for details.
There is NO WARRANTY, to the extent permitted by law.
EOF
  exit 0
}

fatal()
{
  echo "$1" >&2
  echo "Installation failed." >&2
  exit 1
}

usage()
{
  cat <<EOF
Usage: $ME [OPTION]...
Install TrustBridge.

Options:
  -p, --prefix=PATH  install files in PATH
      --help         display this help and exit
      --version      output version information and exit
EOF
  exit $1
}

parse_args()
{
  OPTS=`getopt \
      -l help,prefix:,version \
      -o p: -n "$ME" -- "$@"`
  [ $? -eq 0 ] || usage 23

  eval set -- "$OPTS"

  while true ; do
    case "$1" in
      --prefix|-p)
        instcfg[PREFIX]="$2"
        shift 2
        ;;
      --help)
        usage 0
        ;;
      --version)
        version
        ;;
      --)
        shift
        break
        ;;
    esac
  done
}

write_instcfg()
{
  install -d `dirname "$instcfg_file"`
  echo "# Created by TrustBridge-Installer, don't touch!" >"$instcfg_file"
  for key in "${!instcfg[@]}" ; do
    echo "${key}=${instcfg[$key]}" >>"$instcfg_file"
  done
}

#======================================================================
# main()

parse_args "$@"

cat <<EOF
------------------------------------------------------------------------

   TrustBridge - Installer
   Version ${instcfg[VERSION]}

------------------------------------------------------------------------
EOF

if [ -z "${instcfg[PREFIX]}" ] ; then
    echo -n "Select installation prefix for TrustBridge [${DEFAULT_PREFIX}]: "
    read -e instcfg[PREFIX]

    [ -z "${instcfg[PREFIX]}" ] && instcfg[PREFIX]="${DEFAULT_PREFIX}"
fi

echo "Installing to '${instcfg[PREFIX]}':"

if [ ! -d "${instcfg[PREFIX]}" ] ; then
    echo "creating installation directory ..."
    install -d "${instcfg[PREFIX]}" || fatal "Could not create '${instcfg[PREFIX]}'!"
fi

echo "unpacking files ..."
cd "${instcfg[PREFIX]}"

# ----------------------------------------------------------------------
# regular shar archive inserted here:
###SHAR###
# ----------------------------------------------------------------------

echo "Writing installation configuration to: $instcfg_file ..."
write_instcfg
exit 0
