#!/bin/bash
set -euo pipefail


# Print which dts2repl commits are being compared
OLD_COMMIT="$(<ci-output/dts2repl.version)"
echo "Dashboard repls were generated by dts2repl $OLD_COMMIT, commits since then are:"
git log --oneline --graph --color=always "$OLD_COMMIT..HEAD"

cd ci-output

(
    echo "Generating repls for comparison"
    cd repls/generated

    # shellcheck disable=SC2317
    # shellcheck disable=SC2329
    generate() {
        file=$1

        NAME=$(basename "$file" .dts)
        CMDLINE=()
        CONFIG=../dashboard/"$NAME"-config.json

        # Assemble cmdline based on config
        if [ -f "$CONFIG" ]; then
            while IFS= read -r key; do
                value=$(jq -c --arg k "$key" '.[$k]' "$CONFIG")
                if [[ "$value" =~ ^\[.*\]$ ]]; then
                    # List handling
                    # { item: [value1, value 2] } -> --item value1 --item value2
                    for item in $(jq -r --arg k "$key" '.[$k][]' "$CONFIG"); do
                        CMDLINE+=("--$key" "$item")
                    done
                else
                    # Scalar handling:
                    # { item: value } -> --item=value
                    CMDLINE+=("--$key" "$(jq -r --arg k "$key" '.[$k]' "$CONFIG")")
                fi
            done < <(jq -r 'keys[]' "$CONFIG")
        fi
        echo -n "Generating for $NAME"
        if [ ${#CMDLINE[@]} -eq 0  ]; then
            echo
            dts2repl ../../dts/"$NAME".dts --output "$NAME".repl
        else 
            echo " with custom command-line ${CMDLINE[*]}"
            dts2repl ../../dts/"$NAME".dts --output "$NAME".repl "${CMDLINE[@]}"
        fi
    }
    export -f generate
    parallel generate ::: $(ls ../../dts/*)
    echo "All files generated"
)

# Save diffs for repls that are different
# diff returns 0 on no difference which we use to delete diff files if the
# generated repl is identical (+/- blank lines) to the dashboard one
echo "Generating diffs"

pushd repls/diffs
ls -1 ../generated | parallel 'diff -u --new-file --ignore-blank-lines "../dashboard/{}" "../generated/{}" > "{}.diff" && rm "{}.diff" || true'
popd

if [ "$(ls -A repls/diffs | wc -l)" != 0 ]; then
    echo "Found differences, running Renode"
    RENODE_LOCATION=$(cat ${CI_PROJECT_DIR}/renode-location)
    echo "Renode should be at ${RENODE_LOCATION}"
    export PATH=$(find ${RENODE_LOCATION} -type f -name renode-test | xargs realpath | xargs dirname):$PATH
    renode-test --results-dir robot-results "$PWD/../ci/load_repls_with_diffs.robot"
fi
