#!/bin/sh
# Run the installed abapgen as joern does (abapgen <input> <output-dir>)
# on an ABAP report and a class, and check the OK lines and the JSON.
set -eu
cd "$AUTOPKGTEST_TMP"
mkdir -p in/sub
cat > in/z_demo.prog.abap <<'EOF'
REPORT z_demo.
DATA lv_sum TYPE i.
lv_sum = 1 + 2.
IF lv_sum > 2.
  WRITE 'big'.
ENDIF.
EOF
cat > in/sub/zcl_demo.clas.abap <<'EOF'
CLASS zcl_demo DEFINITION PUBLIC.
  PUBLIC SECTION.
    METHODS run RETURNING VALUE(rv) TYPE i.
ENDCLASS.
CLASS zcl_demo IMPLEMENTATION.
  METHOD run.
    rv = 42.
  ENDMETHOD.
ENDCLASS.
EOF
echo 'not abap' > in/notes.txt
abapgen in out > log
cat log
grep -qx 'OK out/z_demo.prog.json' log
grep -qx 'OK out/sub/zcl_demo.clas.json' log
test "$(wc -l < log)" -eq 2
if abapgen in 2> err; then echo 'FAIL: no error without an output dir'; exit 1; fi
grep -q Usage err
node -e '
const fs = require("fs")
const assert = require("assert/strict")
const read = (f) => JSON.parse(fs.readFileSync(f, "utf8"))
const types = (a) => a.statements.map((s) => s.type)
const prog = read("out/z_demo.prog.json")
assert.equal(prog.file, "z_demo.prog.abap")
assert.equal(prog.objectType, "PROG")
assert.deepEqual(types(prog), ["Report", "Data", "Move", "If", "Write", "EndIf"])
assert.deepEqual(prog.statements[4], {type: "Write",
  tokens: [{str: "WRITE"}, {str: "\x27big\x27"}, {str: "."}],
  start: {row: 5, col: 3}, end: {row: 5, col: 15}})
const clas = read("out/sub/zcl_demo.clas.json")
assert.equal(clas.objectType, "CLAS")
assert.deepEqual(types(clas), ["ClassDefinition", "Public", "MethodDef", "EndClass",
  "ClassImplementation", "MethodImplementation", "Move", "EndMethod", "EndClass"])
console.log("ok: statements, tokens and positions as expected")
'
