#!/usr/bin/env bash
#
# Copyright 2013-2024 Axel Huebl, Rene Widera, Richard Pausch
#
# This file is part of PIConGPU.
#
# PIConGPU 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.
#
# PIConGPU 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 PIConGPU.
# If not, see <http://www.gnu.org/licenses/>.
#

# This script parses template files for a batch systems and fills them
# with a platform-independent configuration, which can then be submitted
# to a batch system or plainly executed. It can also execute additional
# commands at that point, e.g. to copy and archive input files alongside
# a batch job.


#######################
## substitute all `!var` variables given in $1
#
# each line in $1 must contain entries of type `key=value`
########################
function resolve_vars
{
    eval replace_input="\$$1"

    while read -r data_set
    do
        prev="$data_set"
        # loop until all variables are resolved, if nothing is changing because of a cyclic dependency than stop
        while [[ "$data_set" =~ \!([[:alpha:]][[:alnum:]_]*) ]]; do
            var_name="${BASH_REMATCH[1]}"
            # check if variable is defined in the environment
            if [[ -v "$var_name" ]]; then
                var_value="${!var_name}"
                data_set="${data_set/!$var_name/$var_value}"
            else
                # unknown var -> stop replacing to avoid infinite loop
                break
            fi
            [[ "$data_set" == "$prev" ]] && break
            prev="$data_set"
        done
        if [[ "$data_set" =~ \![[:alpha:]][[:alnum:]_]* ]]; then
            echo "Possible cyclic dependency detected or unknown variables used!" >&2
            echo "Check the following varaibles:" >&2
            unresolved_vars=$(printf '%s\n' "$data_set" | grep -o "\![[:alpha:]][[:alnum:]_]*")
            for i in $unresolved_vars; do
                echo "  $i" >&2
            done
        fi

        var="${data_set%%=*}"
        var_value="${data_set#*=}"

        var_value=$(eval echo "$var_value")
        if [[ "$data_set" == *'$('* || "$data_set" == *'${'* ]]; then
          # the right hand side contains expressions in form of $( or ${ therefore we evaluate it explicitly
          export "$var=$var_value"
        else
          # the right hand side is fully resolved so we can evaluate the right hand side
          export "$data_set"
        fi
    done < <(echo "$replace_input" | grep "^[[:alpha:]][[:alnum:]_]*=.*" )
}

#######################
## substitute all `!var` variables given in $1
########################
function resolve_data_stream
{
    eval data="\$$1"

    while IFS= read -r data_set
    do
        prev="$data_set"
        while [[ "$data_set" =~ \!([[:alpha:]][[:alnum:]_]*) ]]; do
            var_name="${BASH_REMATCH[1]}"
            # check if variable is defined in the environment
            if [[ -v "$var_name" ]]; then
                var_value="${!var_name}"
                data_set="${data_set/!$var_name/$var_value}"
            else
                break
            fi
            [[ "$data_set" == "$prev" ]] && break
            prev="$data_set"
        done
        if [[ "$data_set" =~ \![[:alpha:]][[:alnum:]_]* ]]; then
            echo "Unknown variables used in template file!" >&2
            echo "Check the following varaibles:" >&2
            unresolved_vars=$(printf '%s\n' "$data_set" | grep -o '![[:alpha:]][[:alnum:]_]*')
            for i in $unresolved_vars; do
                echo "  $i" >&2
            done
        fi

        echo "$data_set"
    done <<< "$data"
}

#######################
## apply extra overwrite variables
#
# overwrite variable definition from $1 if defined in $2
#
# $1 data stream where variables should be overwritten
# $2 data stream with overwrite template parameter definitions (tbg parameter -o)
#######################
function apply_extra_vars
{
    eval data="\$$1"
    eval extra_op="\$$2"
    while read -r data_set
    do
        if [[ "$data_set" =~ ^[[:space:]]*[[:alpha:]][[:alnum:]_]*=.* ]]; then
            # get variable name (left side of assign)
            var="${data_set%%=*}"
            # check if variable must be overwritten
            op=""
            for word in $extra_op; do
                if [[ "$word" == "$var="* ]]; then
                    op="$word"
                    break
                fi
            done
            if [[ -n "$op" ]]; then
                echo "$op"
            else
                # data_set is a assignment but variable not contained in $2
                echo "$data_set"
            fi
        else
            # data_set is no assignment, therefore write out without changes
            echo "$data_set"
        fi
    done <<< "$data"
}

#######################
## Set environment variables in the current environment from a list
#
# each line in $1 must contain entries of type `key=value`
#
# $1 data stream where variables should be overwritten
#######################
function set_env_vars
{
    eval data="\$$1"
    while read -r data_set
    do
       export "$data_set"
    done <<< "$data"
}

#######################
## get substituted variables
#
# replace recursive all `!var` variables in a list of variable definition
#
# $1 data path and name to submit script
# $2 tpl file data
# $3 data stream with overwrite template parameter definitions (tbg parameter -o)
#######################
function run_cfg_and_set_solved_variables
{
    eval file_data="\$$2" #data stream from tpl file
    eval extra_op="\$$3"    #overwrite templates with extra options parameter -o

    # merge multi line to single line
    cfg_script=$(sed -e :a -e '/\\\\$/N; s/\\\\\n//; ta' $1)

    # overwrite variable definition if contained in $3
    cfg_script_overwritten=$(apply_extra_vars cfg_script extra_op)

    # execute the cfg script
    eval "$cfg_script_overwritten" # name and path to cfg file

    # collect variable definitions from the cfg file
    cfg_script_overwritten_vars=$(echo -e "$cfg_script_overwritten" | grep -o '^[[:blank:]]*[[:alpha:]][[:alnum:]_]*' | tr -d "=")
    cfg_script_overwritten_vars=$(echo -e "$cfg_script_overwritten_vars" | sort | while read var; do [ -z "${!var}" ] || echo $var=${!var} ; done)

    # get all variable assignments (form: `.var=value`) from the tpl file
    tbg_vars=$(echo "$file_data" | grep "^[[:blank:]]*\.[[:alpha:]][[:alnum:]_]*=.*" | sed 's/^[[:blank:]]*\.//')

    # overwrite all variable assignments from tpl file with overwrite variables
    tbg_vars_overwritten=`apply_extra_vars tbg_vars extra_op`

    set_env_vars tbg_vars_overwritten
    all_tbg_vars=$(echo -e "$tbg_vars_overwritten\n$cfg_script_overwritten_vars")
    resolve_vars all_tbg_vars

    # evaluate all variable assignments which are contained in the tpl file
    # variables are already set in the environment and resolved
    while read -r data_set
    do
        var_name=$(echo -e "$data_set" | cut -d"=" -f1)
        var_value=$(eval echo \$$var_name)
        if [ -n  "$var_value" ] ; then
            export "$var_name=$var_value"
        fi
    done < <(echo "$all_tbg_vars" |  grep "^[[:blank:]]*[[:alpha:]][[:alnum:]_]*=.*")
}

#######################
# $1 path to final file
# $2 content of the original file
#######################
function check_final
{
    final_file="$1"
    org_file="$2"

    not_replaced=$(grep -o '![[:alpha:]][[:alnum:]_]*' $final_file | sort | uniq)
    not_replaced_cnt=$(echo $not_replaced | wc -w)

    if [ $not_replaced_cnt -gt 0 ] ; then
        echo "ERROR: $not_replaced_cnt variable(s) _not_ replaced from template (tpl):"
        echo $not_replaced

        #create an OR concated pattern
        nrv_or=$(echo $not_replaced | sed 's/[[:space:]]/|/g')

        #search in orginal file, to provide a better line number hint to the user
        n=0
        while read -r org_line
        do
            n=$(( n+1 ))
            echo $org_line | awk -v line=$n '{ if ($0 ~ /'$nrv_or'/) print "line "line }'
        done < <(echo "$org_file")

        # abort script (will not be submitted)
        exit 1
    fi
}

function absolute_path()
{
    cd $1
    pwd
}

help()
{
    echo "TBG (template batch generator)"
    echo "create a new folder for a batch job and copy in all important files"
    echo ""
    echo "usage: tbg -c [cfgFile] [-s [submitsystem]] [-t [templateFile]]"
    echo "          [-o \"VARNAME1=10 VARNAME2=5\"] [-f] [-h]"
    echo "          [projectPath] destinationPath"
    echo ""
    echo "recommended usage when sourcing a PIConGPU config file before:"
    echo "    tbg -s -t -c cfgFile destinationPath"
    echo ""
    echo "-c | --cfg      [file]         - Configuration file to set up batch file."
    echo "                                 Default: [cfgFile] via export TBG_CFGFILE"
    echo "-s | --submit   [command]      - Submit command (qsub, \"qsub -h\", sbatch, ...)"
    echo "                                 Default: [submitsystem] via export TBG_SUBMIT"
    echo "-t | --tpl      [file]         - Template to create a batch file from."
    echo "                                 tbg will use stdin, if no file is specified."
    echo "                                 Default: [templateFile] via export TBG_TPLFILE"
    echo "                                 Warning: If -t is omitted, stdin will be used as"
    echo "                                 input for the template."
    echo "-o                             - Overwrite any template variable:"
    echo "                                 spaces within the right side of assign are not allowed"
    echo "                                 e.g. -o \"VARNAME1=10 VARNAME2=5\""
    echo "                                 Overwriting is done after cfg file was executed"
    echo "-f | --force                   - Override if 'destinationPath' exists."
    echo "-h | --help                    - Shows help (this output)."
    echo ""
    echo "[projectPath]                  - Project directory containing source code and"
    echo "                                 binaries"
    echo "                                 Default: current directory"
    echo "destinationPath                - Directory for simulation output. "
    echo " "
    echo " "
    echo "TBG exports the following variables, which can be used in cfg and tpl files at"
    echo "any time:"
    echo " TBG_jobName                   - name of the job"
    echo " TBG_jobNameShort              - short name of the job, without blanks"
    echo " TBG_cfgPath                   - absolute path to cfg file"
    echo " TBG_cfgFile                   - full absolute path and name of cfg file"
    echo " TBG_projectPath               - absolute project path (see optional parameter"
    echo "                                 projectPath)"
    echo " TBG_dstPath                   - absolute path to destination directory"
}

#!/usr/bin/env bash
#Check whether the provided path is relative or absolute and
#convert it to an abolute path
script=$0

absScriptPath=$(realpath $0)
initCall="cd $(pwd); $absScriptPath $*"
projectPath="."

pathToegetopt=$(which egetopt 2>/dev/null)
if [ $? -eq 0 ] ; then
    pathToegetopt=$(dirname $pathToegetopt)
else
    pathToegetopt=$(dirname $0)
fi

egetoptTool=$(which $pathToegetopt/egetopt 2>/dev/null)
if [ $? -ne 0 ] ; then
    echo "Cannot find program egetopt" >&2
    exit 1
fi

# options may be followed by
# - one colon to indicate they has a required argument
# - two colons to indicate they has a optional argument
OPTS=$($egetoptTool -o t::c::s::o:fh -l tpl::,cfg::,submit::,force,help -n tbg ++ "$@")
if [ $? != 0 ] ; then
    # something went wrong, egetopt will put out an error message for us
    exit 1
fi

eval set -- "$OPTS"

# parser
while true ; do
    case "$1" in
        -s|--submit)
            submit_command=${2:-$TBG_SUBMIT}
            if [ -z "$submit_command" ] ; then
                echo "missing submit command for -s|--submit" >&2
                exit 1
            fi
            shift
            ;;
       -c|--cfg)
            cfg_file=${2:-$TBG_CFGFILE}
            shift
            ;;
       -o)
            overwrite_vars="$2"
            shift
            ;;
       -f|--force)
            force="true"
            ;;
       -t|--tpl)
            template_file_name=${2:-$TBG_TPLFILE}
            shift
            ;;
        -h|--help)
            echo -e "$(help)"
            shift
            exit 0
            ;;
        --) shift; break;;
    esac
    shift
done

# tpl file was set - does it also exist?
#   if a tpl file was not set, try stdin later on
if [ -n "$template_file_name" ] && [ ! -f "$template_file_name" ] ; then
    echo "The given tpl file \"$template_file_name\" does not exist (-t|--tpl)." >&2
    exit 1;
fi

if [ -z "$*" ] ; then
    echo "No output directory is set (last tbg parameter)." >&2
    exit 1;
fi

# the first parameter is the project path
if [ $# -ge 2 ] ; then
    projectPath="$1"
    shift
fi

# the parameter list was shifted in the `if` block before
# only one parameter is allowed
# an empty parameter list is handled later
if [ $# -ge 2 ] ; then
    echo "To many output directories are given '$*'" >&2
    exit 1;
fi

# the last parameter is the `destinationPath`
outDir="$1"

if [ -z "$cfg_file" ] ; then
    echo "No cfg file given (-c|--cfg)." >&2
    exit 1;
fi

if [ ! -f "$cfg_file" ] ; then
    echo "The given cfg file \"$cfg_file\" does not exist (-c|--cfg)." >&2
    exit 1;
fi

# cfg file sanity check - space after \ at EOL ?
cfg_err=$(grep -cE '\\[[:blank:]]+$' $cfg_file)
if [ $cfg_err != 0 ] ; then
    echo "ERROR: file \"$cfg_file\" contains spaces after line continuation \\"
    echo "Check the following lines for end-of-line spaces:"
    echo ""
    grep -nE '\\[[:blank:]]+$' $cfg_file
    echo ""
    echo "Run the following command on the file to remove your"
    echo "end-of-line (EOL) white spaces:"
    echo ""
    echo "sed -i 's/[[:blank:]]\\+$//' $cfg_file"
    exit 1;
fi

# cfg file sanity check - windows EOL? (CR LF)
cfg_err=$(grep -c $'\r' $cfg_file)
if [ $cfg_err != 0 ] ; then
    echo "ERROR: file \"$cfg_file\" contains" $cfg_err "non-unix new lines (\r)."
    echo ""
    echo "Run the following command on the file to convert all line endings"
    echo "to pure unix line endings:"
    echo ""
    echo "dos2unix $cfg_file"
    exit 1;
fi

projectPath=$(absolute_path $projectPath)

job_name=$(basename "$outDir")
# (up to 15 characters, no blank spaces, reduce to alphanumeric characters)
job_shortname=$(echo $job_name | sed "s/[^a-zA-Z0-9]//g" | cut -c1-15)
job_relative_dir=$(dirname "$outDir")



#create relative dir that we can jump in and check absolute dir
mkdir -p "$job_relative_dir"
if [ $? -ne 0 ] ; then
    echo "Could not create directory in: $job_relative_dir" >&2
    exit 1
fi
job_outDir="$(absolute_path $job_relative_dir)/$job_name"

if [ -z "$template_file_name" ] ; then
    template_file_data=$(cat /dev/stdin)
else
    template_file_data=$(cat "$template_file_name")
fi
# read picongpu params

start_dir=$(dirname $0)

if [ -d "$job_outDir" ] ; then
    if [ "$force" == "true" ] ; then
        echo "Warning: using existing folder on user-request [-f]"
    else
        echo "Destination path already in use, cannot create new folder" >&2
        exit 1
    fi
fi

#set TBG variables which can used in cfg and tpl file
#export is used that we can call new scripts in cfg and can read this variables in the called script
export TBG_jobName="$job_name"
export TBG_jobNameShort="$job_shortname"

cfgFileName=$(basename $cfg_file)
cfgRelativPath=$(dirname $cfg_file)
export TBG_cfgPath=$(absolute_path "$cfgRelativPath")
export TBG_cfgFile="$TBG_cfgPath/$cfgFileName"

if [ ! -z "$template_file_name" ] ; then
    tplAbsolutePath="$(absolute_path $(dirname $template_file_name))/$(basename $template_file_name)"
fi

export TBG_projectPath="$projectPath"
export TBG_dstPath="$job_outDir"

mkdir -p "$job_outDir"
if [ $? -ne 0 ] ; then
    echo "Could not create directory in: $job_outDir" >&2
    exit 1
fi
mkdir -p "$job_outDir/tbg"
cd "$job_outDir"

# Add -o args to env to allow for all variables used in the *.tpl file to be set through the -o option
for i in $overwrite_vars; do
    export $i
done

# get the full replaced and evaluated variable definitions
run_cfg_and_set_solved_variables "$TBG_cfgFile" template_file_data overwrite_vars

#delete all variable assignments (form: `.var=value`) from the tpl file
template_file_data_cleaned=$(echo "$template_file_data" |  grep -v "^[[:blank:]]*\.[[:alpha:]][[:alnum:]_]*=.*")
# create the content of the batch system file `submit.start`
batch_file=$(resolve_data_stream template_file_data_cleaned)

if [ ! -z "$template_file_name" ] ; then
    # preserve file attributes/permissions
    cp -a $tplAbsolutePath tbg/submit.start
fi
# overwrite copied content but keep permissions (or create file if tpl comes from stdin)
echo "$batch_file" > tbg/submit.start
echo -e "\n#this script was created with call $initCall" >> tbg/submit.start
echo "$template_file_data" > tbg/submit.tpl
cp -a "$TBG_cfgFile" tbg/submit.cfg

#warn, if there are still unresolved !TBG_ variables left
check_final tbg/submit.start "$template_file_data"

if [ -n "$submit_command" ] ; then
    $submit_command tbg/submit.start
else
    echo "nothing to submit (-s option set?)"
fi
