#!/bin/sh

# Script to install the CTDB testsuite on a machine.

usage ()
{
    if [ -n "$1" ] ; then
	echo "$1"
	echo
    fi

    cat <<EOF
  $0 --destdir=<DIR1> \\
     --datarootdir=<DIR2>  \\
     --libdir=<DIR3> \\
     --bindir=<DIR4> \\
     --etcdir=<DIR5>
EOF
    exit 1
}

parse_options ()
{
    temp=$(getopt -n "$prog" -o "h" -l help,destdir:,datarootdir:,libdir:,bindir:,etcdir: -- "$@")

    [ $? != 0 ] && usage

    eval set -- "$temp"

    destdir=""
    datarootdir=""
    libdir=""
    bindir=""
    etcdir=""

    while true ; do
        case "$1" in
            --destdir) destdir="$2" ; shift 2 ;;
            --datarootdir) datarootdir="$2" ; shift 2 ;;
            --libdir) libdir="$2" ; shift 2 ;;
            --bindir) bindir="$2" ; shift 2 ;;
            --etcdir) etcdir="$2" ; shift 2 ;;
            --) shift ; break ;;
            -h|--help|*) usage ;; # Shouldn't happen, so this is reasonable.
        esac
    done

    [ $# -gt 0 ] && usage

    [ -n "$destdir" ]     || usage "No option --destdir specified"
    [ -n "$datarootdir" ] || usage "No option --datarootdir specified"
    [ -n "$libdir" ]      || usage "No option --libdir specified"
    [ -n "$bindir" ]      || usage "No option --bindir specified"
    [ -n "$etcdir" ]      || usage "No option --etcdir specified"
}

parse_options "$@"

# Make things neater!
if [ "$destdir" = "/" ] ; then
    destdir=""
fi

data_subdirs="complex events.d eventscripts onnode scripts simple takeover tool"

ctdb_datadir="${destdir}${datarootdir}/ctdb-tests"
echo "Installing test data files into ${ctdb_datadir}..."
for d in $data_subdirs ; do
    mkdir -p "${ctdb_datadir}/${d}"
    cp -pr "tests/${d}" "${ctdb_datadir}"
done
# Some of the unit tests have relative symlinks back to in-tree bits
# and pieces.  These links will be broken!
for i in "events.d" "functions" "nfs-rpc-checks.d" ; do
    ln -sf "${etcdir}/ctdb/${i}" "${ctdb_datadir}/eventscripts/etc-ctdb/${i}"
done
# test_wrap needs to set TEST_BIN_DIR
sed -i -e "s@^TEST_SCRIPTS_DIR=.*@&\nexport TEST_BIN_DIR=\"${libdir}/ctdb-tests\"@" "${ctdb_datadir}/scripts/test_wrap"

ctdb_libdir="${destdir}${libdir}/ctdb-tests"
mkdir -p  "${destdir}${libdir}"
echo "Installing test binary files into ${ctdb_libdir}..."
cp -pr "tests/bin/" "${ctdb_libdir}"

ctdb_bindir="${destdir}${bindir}"
echo "Installing wrapper scripts into ${ctdb_bindir}..."
mkdir -p "${ctdb_bindir}"
out="${ctdb_bindir}/ctdb_run_tests"
sed -e "s@^test_dir=.*@test_dir=${datarootdir}/ctdb-tests\nexport TEST_BIN_DIR=\"${libdir}/ctdb-tests\"@" "tests/run_tests.sh" >"$out"
chmod 755 "$out"
ln -s "ctdb_run_tests" "${ctdb_bindir}/ctdb_run_cluster_tests"
