#!/bin/bash
#   As we want to create jobs for individual tables, due to the limitation of the 
#   ci "language" we would need to create many many blocks of code for each table in 
#   .gitlab-ci.yml, which would be very annoying. This script, combined with the ci-template
#   can be used to procedurally generate a yaml file containing the necessary job specs
#   for the table summary and check delta jobs, for each table specified in the 'tables' list
#
#   Clint Seinen 2019-03-15
#
tables='3hr 6hrLev 6hrPlev 6hrPlevPt AERday AERhr AERmon AERmonZ Amon CF3hr CFday CFmon CFsubhr E1hr E3hr E3hrPt Eday EdayZ Efx Emon EmonZ Eyr IfxAnt IfxGre ImonAnt ImonGre LImon Lmon Oclim Oday Ofx Omon Oyr SIday SImon day fx'
stages=( "summarize_tables" "check_deltas" )
stage_flag=( "-t" "-d" )
output_f='tmp.yml'

[ -e "$output_f" ] && rm -f $output_f
touch $output_f

# loop over tables and create ci for each table
for tab in $tables; do 
    
    # loop over different stages
    for ((i=0;i<${#stages[@]};++i)); do
        # output template to file
        cat ci-template >> $output_f

        # if verify stage, add line to allow failures
        if [ "${stages[i]}" = "summarize_tables" ]; then
            # allow for failures
            printf "    allow_failure: true\n" >> $output_f

            # add "verify-conv" to jobname
            jobname="${tab}-summary"
        else
            jobname="${tab}-deltas"
        fi

        # replace JOBNAME, STAGE, TABLE, and SCRIPT in file
        sed -i "s/JOBNAME/${jobname}/g" $output_f
        sed -i "s/TABLE/${tab}/g" $output_f
        sed -i "s/STAGE/${stages[i]}/g" $output_f
        sed -i "s/FLAG/${stage_flag[i]}/g" $output_f

        # add newline for neatness
        printf "\n" >> $output_f
    done
done

