#!/bin/sh
# 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 ...
[ -z "${PORTWARE_CODESYS_SKIP:-}" ] || exit 0

ROOT=$(git rev-parse --show-toplevel) || exit 1
cd "$ROOT" || 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
    sh .portware/codesys/export.sh "$file" || exit 1
    git add -- "${file%.*}.xml" || exit 1
done < "$LIST"
exit 0
