#!/bin/bash
#----------------------------------------------------------------------------
# Get current version
source ../../bin/version.sh
odbver=${OP_VERSION_SHORT,,}
odbver=${odbver//-/_}

PACKAGE=../../build/${odbver}.tgz
[[ -f $PACKAGE ]] || {
    echo "error: no package file found at <$PACKAGE> - need to run makepkg.sh" 1>&2
    exit 255
}
echo ">>> Setup version $OP_VERSION"
echo ">>> Package: $PACKAGE"

# create install and work environment
echo ">>> Create base environment"
mkdir -p RunLogs   || exit 255   # logs for run_test.sh
mkdir -p local/bin || exit 255   # install bin directory
mkdir -p package   || exit 255   # where package  is untarred
mkdir -p work      || exit 255   # work root

if [[ ! -f package/install_pkg.sh ]]; then
    echo ">>> untarring $PACKAGE into $(pwd)/package"
    tar -xzf $PACKAGE -C ./package  --strip-components=1 || exit 255
else
    echo ">>> package is already untarred at $(pwd)/package"
fi

export PREFIX=$(pwd)/local
if [[ -f $PREFIX/bin/ODB-mapper ]]; then
    echo ">>> SKIP: package is already installed"
else
    echo ">>> Install package in prefix $PREFIX"
    [[ -f package/install_pkg.sh ]] || { echo "error: missing install_pkg.sh in $(pwd)/package"; exit 255; }
    {
        cd package
        ./install_pkg.sh || {
            echo "" 1>&2
            echo "error: failed installing package" 1>&2
            echo "" 1>&2
            exit 255
        }
    } >& install_pkg.log
    echo ">>> install done"
fi

exit 0
