#!/bin/sh
# run this script inside the folder with the BPMN files that need to be patched
# This script depends on the surefire report that is generated by the test in the bpmn-db-utils folder
SUREFIRE_REPORT="../surefire-reports/com.camunda.consulting.bpmn_validator.DeploymentTest.txt"

# list all errors reported by the Camunda Engine Parser
egrep "^\* " $SUREFIRE_REPORT


#* Invalid source 'boundarysignal8' of sequence flow 'flow191' | abc.bpmn | line 90 | column 95
REGEXP_SEQUENCE_FLOW_NOT_IN_SUBPROCESS="Invalid source '([^']+)' of sequence flow '([^']+)' \| (.+) \| line [0-9]+ \| column [0-9]+"

egrep -o "$REGEXP_SEQUENCE_FLOW_NOT_IN_SUBPROCESS" "$SUREFIRE_REPORT" \
  | sed -r "s#$REGEXP_SEQUENCE_FLOW_NOT_IN_SUBPROCESS#xmlstarlet select -t -v \"//*[child::*/@id='\1']/@id\" -o '\\n' -c \"//*[@id='\2']\" -o '\\n' \3#" \
  | sh  \
  | sed -e 's/ xmlns[^=]*="[^"]*"//g' -e 's#/><#/>\n<#g' \
  | pygmentize -l xml
egrep -o "$REGEXP_SEQUENCE_FLOW_NOT_IN_SUBPROCESS" "$SUREFIRE_REPORT" \
  | sed -r "s#$REGEXP_SEQUENCE_FLOW_NOT_IN_SUBPROCESS#xmlstarlet edit --inplace --pf --move \"//*[@id='\2']\" \"//*[child::*/@id='\1']\" \3#"


egrep -o "$REGEXP_SEQUENCE_FLOW_NOT_IN_SUBPROCESS" "$SUREFIRE_REPORT" \
  | sed -r "s#$REGEXP_SEQUENCE_FLOW_NOT_IN_SUBPROCESS#xmlstarlet edit --inplace --pf --move \"//*[@id='\2']\" \"//*[child::*/@id='\1']\" \3#" \
  | sh  \


#* Invalid reference targetRef 'boundaryerror22' of association element  | abc.bpmn | line 154 | column 92
#* Invalid reference sourceRef 'textannotation3' of association element  | abc.bpmn | line 198 | column 106
REGEXP_DANGLING_ASSOCIATION="Invalid reference (sourceRef|targetRef) '([^']+)' of association element  \| (.+) \| line [0-9]+ \| column [0-9]+"

DANGLING_ASSOCIATION_ERRORS=$(egrep -o "$REGEXP_DANGLING_ASSOCIATION" "$SUREFIRE_REPORT")
DANGLING_ASSOCIATION_XPATH="//bpmn:association[@\1='\2']"
DANGLING_ASSOCIATION_XMLSTARLET_SELECT=$(echo "$DANGLING_ASSOCIATION_ERRORS" \
  | sed -r "s#$REGEXP_DANGLING_ASSOCIATION#xmlstarlet select -N bpmn=\"http://www.omg.org/spec/BPMN/20100524/MODEL\" -t -c \"$DANGLING_ASSOCIATION_XPATH\" -o '\\n' \3#")
echo "$DANGLING_ASSOCIATION_XMLSTARLET_SELECT"
sh -c "$DANGLING_ASSOCIATION_XMLSTARLET_SELECT" \
  | sed -e 's/ xmlns[^=]*="[^"]*"//g' -e 's#/><#/>\n<#g' \
  | pygmentize -l xml
DANGLING_ASSOCIATION_XMLSTARLET_EDIT=$(echo "$DANGLING_ASSOCIATION_ERRORS" \
  | sed -r "s#$REGEXP_DANGLING_ASSOCIATION#xmlstarlet edit --inplace --pf -N bpmn=\"http://www.omg.org/spec/BPMN/20100524/MODEL\" --delete \"$DANGLING_ASSOCIATION_XPATH\" \3#")
echo "$DANGLING_ASSOCIATION_XMLSTARLET_EDIT"
sh -c "$DANGLING_ASSOCIATION_XMLSTARLET_EDIT"
