#!/bin/sh
# PORTWARE-CODESYS-KIT
# PORTWARE Git Studio: every committed CODESYS .project carries its PLCopen XML.
# A .project is binary. Without a current export beside it, Git Studio would
# show and compare the previous program, so a failed export stops the commit.
# Emergency exit, for one commit: PORTWARE_CODESYS_SKIP=1 git commit ...
# The CODESYS toolbar's Send exports from the open window first and says so
# with PORTWARE_CODESYS_EXPORTED=1: the export is then only checked, not redone
# (a second CODESYS could not open the project the first one holds).
[ -z "${PORTWARE_CODESYS_SKIP:-}" ] || exit 0

ROOT=$(git rev-parse --show-toplevel) || exit 1
cd "$ROOT" || exit 1
# The export install.sh copied into the Git folder, never the one a pushed
# commit could have changed.
RUN=$(git rev-parse --git-path portware-codesys) || exit 1

LIST=$(mktemp "${TMPDIR:-/tmp}/portware-staged.XXXXXX") || exit 1
trap 'rm -f "$LIST"' EXIT
git diff --cached --name-only --diff-filter=ACMR -- '*.project' > "$LIST"

while IFS= read -r file; do
    [ -n "$file" ] || continue
    if [ -n "$(git diff --name-only -- "$file")" ]; then
        echo "PORTWARE: $file changed after it was staged. Stage it again, then commit." >&2
        exit 1
    fi
    if [ -n "${PORTWARE_CODESYS_EXPORTED:-}" ]; then
        if [ ! -f "${file%.*}.xml" ]; then
            echo "PORTWARE: ${file%.*}.xml is missing: the export from the CODESYS window did not run." >&2
            exit 1
        fi
    else
        if [ ! -f "$RUN/export.sh" ]; then
            echo "PORTWARE: Connect for CODESYS is not installed in this clone. Run: sh .portware/codesys/install.sh" >&2
            exit 1
        fi
        sh "$RUN/export.sh" "$file" || exit 1
    fi
    git add -- "${file%.*}.xml" || exit 1
done < "$LIST"
exit 0
