#!/bin/bash

# THIS FILE IS PART OF THE CYLC SUITE ENGINE.
# Copyright (C) 2008-2019 NIWA & British Crown (Met Office) & Contributors.
#
# 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() {
    cat << __END__
Usage: cylc import-examples DIR

Copy the cylc example suites to DIR and register them for use under the GROUP
suite name group.

Arguments:
   DIR    destination directory
__END__
}

if [[ $1 == '-h' || $1 == '--help' ]]; then
    usage
    exit 0
fi

if [[ -z $CYLC_DIR ]]; then
    echo "ERROR: \$CYLC_DIR is not defined. Run this script via" >&2
    echo "the main command interface: 'cylc import-examples'" >&2
    exit 1
fi

if [[ $# -gt 2 ]] || [[ $# -lt 1 ]]; then
    usage >&2
    exit 1
fi

TOP_DIR=$1
BASE_DIR=examples/$(cylc --version)
DESTINATION=$TOP_DIR/cylc-$BASE_DIR
if [[ -d $DESTINATION ]]; then
    echo "ERROR: $DESTINATION already exists." >&2
    exit 1
fi

echo " + Copying example suites"
mkdir -p $DESTINATION
cp -r $CYLC_DIR/etc/examples/* $DESTINATION

echo " + Registering example suites"
cd $DESTINATION
SUITE_RCS=$(find . -name suite.rc | sed -e 's@./@@')
for SUITE_RC in $SUITE_RCS; do
    SUITE_DEF_DIR=$(dirname $SUITE_RC)
    SUITE_REG_NAME=$BASE_DIR/$SUITE_DEF_DIR
    cylc register $SUITE_REG_NAME $SUITE_DEF_DIR
done

echo "DONE"
