#!/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 ""
    echo "Usage: cylc [admin] import-examples DIR [GROUP]"
    echo ""
    echo "Copy the cylc example suites to DIR/GROUP and register"
    echo "them for use under the GROUP suite name group."
    echo ""
    echo "Arguments:"
    echo "   DIR    destination directory"
    echo "   GROUP  suite name group (default: cylc-<version>)"
}

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 admin import-examples'" >&2
    exit 1
fi

if [[ $# > 2 ]] || [[ $# < 1 ]]; then
    usage >&2
    exit 1
fi

DIR=$1

if [[ $# == 2 ]]; then
    TOPGRP=$2
else
    TOPGRP=cylc-$( cylc -v | tr '.' '-' )
fi

if $( cylc db print --fail $TOPGRP > /dev/null 2>&1 ); then
    echo "ERROR: the $TOPGRP name group already exists." >&2
    echo " Reregister it, or choose another name group." >&2
    exit 1
fi

TOPDIR=$DIR/$TOPGRP

if [[ -d $TOPDIR ]]; then
    echo "ERROR: $TOPDIR already exists." >&2
    echo "Remove it or choose another DIR." >&2
    exit 1
fi

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

echo " + Registering example suites"
cd $TOPDIR
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=${TOPGRP}.$( echo $SUITE_DEF_DIR | tr '/' '.' )
    cylc db register $SUITE_REG_NAME $SUITE_DEF_DIR
done

echo "DONE"
