#!/bin/bash

set -e

TEMPLATE=${1:-"ag_parameters"}
PREFIX=${2:-"param"}

log() {
    echo "-#- $@" >&2
}

die() {
    echo "ERROR: $@" >&2
    exit 2
}

test -r "$TEMPLATE" || die "file not found: $TEMPLATE"

source "$TEMPLATE" || die "cannot read file: $TEMPLATE"
declare -a common_opts=( "${MORE_ARGS[@]}" )

for flavour in "I" "R"; do
    for distrib in "1" "N"; do
        for ratio in "1000:1" "100:1" "10:1" "1:1" "1:10" "1:100" "1:1000"; do
            declare -a opts=( "${common_opts[@]}" )
            case "$flavour" in
                "I") opts+=( -Z ) ;;
                "R") : ;;
                *) die "unknown flavour: $flavour" ;;
            esac
            case "$distrib" in
                "1") : ;;
                "N") opts+=( -r42 -R ) ;;
                *) die "unknown distribution: $distrib" ;;
            esac
            case "$ratio" in
                "1000:1") opts+=( -c1e6,0 -C1.25e2,0 ) ;;
                "100:1")  opts+=( -c1e6,0 -C1.25e3,0 ) ;;
                "10:1")   opts+=( -c1e6,0 -C1.25e4,0 ) ;;
                "1:1")    opts+=( -c1e6,0 -C1.25e5,0 ) ;;
                "1:10")   opts+=( -c1e6,0 -C1.25e6,0 ) ;;
                "1:100")  opts+=( -c1e6,0 -C1.25e7,0 ) ;;
                "1:1000") opts+=( -c1e6,0 -C1.25e8,0 ) ;;
                *) die "unknown ratio: $ratio" ;;
            esac
            suffix="${flavour}${distrib}_${ratio}"
            output="${PREFIX}_${suffix}"
            more_args="${opts[@]}"
            results="./results_${suffix}"
            log "writing file: ${output}"
            {
                sed -n '/MORE_ARGS/q;p' "$TEMPLATE"
                printf 'MORE_ARGS=( %s )\n' "${more_args}"
                sed -n '1,/MORE_ARGS/d;/RESULTS/q;p' "$TEMPLATE"
                printf 'RESULTS="%s"\n' "${results}"
                sed '1,/RESULTS/d' "$TEMPLATE"
            } > "${output}"
        done
    done
done