#!/bin/bash

# THIS FILE IS PART OF THE CYLC SUITE ENGINE.
# Copyright (C) 2008-2016 NIWA
#
# 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 program 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 this program.  If not, see <http://www.gnu.org/licenses/>.

set -e

usage() {
    echo "Usage: cylc [admin] test-db [--help]"
    echo "A thorough test of suite registration database functionality."
    echo "Options:"
    echo "  --help   Print this usage message."
}

if [[ $# != 0 ]]; then
    usage
    if [[ $1 == "--help" ]]; then
        exit 0
    else
        echo "ERROR: illegal command line arguments" >&2
        exit 1
    fi
fi

MY_TMPDIR=${MY_TMPDIR:-${TMPDIR:-/tmp}}
mkdir -p $MY_TMPDIR

# seconds since epoch
SSE=$( date +%s )

GRP=testdb.$SSE
REG1=${GRP}.foooo123
REG2=${GRP}.baaar123
REG3=${GRP}.baaaz123
REG4=${GRP}.waaaz123
REG5=${GRP}.impppt123

# clean up old suite def dirs from any aborted previous run
rm -rf $MY_TMPDIR/$REG4
rm -rf $MY_TMPDIR/$REG5

echo
echo "> TEST1: register a cylc example suite as $REG1"
DEFDIR=$MY_TMPDIR/test-db.$SSE
cp -r $CYLC_DIR/examples/admin $DEFDIR
echo cylc db reg $REG1 $DEFDIR
cylc db reg $REG1 $DEFDIR

echo
echo "> TEST2: reregister $REG1 as $REG2"
echo cylc db rereg $REG1 $REG2
cylc db rereg $REG1 $REG2

echo
echo "> TEST3: copy $REG2 to $REG3 (registration only)"
echo cylc db register $REG3 $(cylc db get $REG2)
cylc db register $REG3 $(cylc db get $REG2)

echo
echo "> TEST4: copy the suite to $REG4"
echo cylc db copy $REG2 $REG4 $MY_TMPDIR/$REG4
cylc db copy $REG2 $REG4 $MY_TMPDIR/$REG4

echo
echo "> TEST5: print DB reg group $GRP"
echo cylc db pr $GRP
cylc db pr $GRP

echo
echo "> TEST13: unregister $REG2 from DB"
echo cylc db unreg $REG2
cylc db unreg $REG2

echo
echo "> TEST14: delete the rest of group $GRP from DB"
echo cylc db unreg --delete -f $GRP
cylc db unreg --delete -f "${GRP}\..*"

echo
echo "> TEST16: print DB group $GRP (should be empty)"
echo cylc db pr $GRP
cylc db pr $GRP

echo
echo "> All database tests passed."
