#!/bin/bash
# https://docs.sheetjs.com/docs/demos/engines/jerryscript
cd /tmp
rm -rf SheetJSJerry
mkdir -p SheetJSJerry
cd SheetJSJerry

git clone --depth=1 https://github.com/jerryscript-project/jerryscript.git
cd jerryscript
python3 tools/build.py --error-messages=ON --logging=ON --mem-heap=8192 --cpointer-32bit=ON
cd ..

curl -LO https://cdn.sheetjs.com/xlsx-latest/package/dist/xlsx.full.min.js
curl -LO https://cdn.sheetjs.com/xlsx-latest/package/dist/shim.min.js
curl -LO https://sheetjs.com/pres.xlsx

# Integration Example
curl -LO https://docs.sheetjs.com/jerryscript/sheetjs.jerry.c

gcc -o sheetjs.jerry -Ijerryscript/jerry-ext/include -Ijerryscript/jerry-math/include -Ijerryscript/jerry-core/include sheetjs.jerry.c -ljerry-core -ljerry-ext -ljerry-port -lm -Ljerryscript/build/lib -Wno-pointer-sign
./sheetjs.jerry pres.xlsx; echo $?

# CLI Test
node -e "fs.writeFileSync('payload.js', 'var payload = \"' + fs.readFileSync('pres.xlsx').toString('base64') + '\";')"

cat >global.js <<EOF
var global = (function(){ return this; }).call(null);
var console = { log: function(x) { print(x); } };
EOF

cat >jerry.js <<EOF
var wb = XLSX.read(payload, {type:'base64'});
console.log(XLSX.utils.sheet_to_csv(wb.Sheets[wb.SheetNames[0]]));
EOF

cat global.js xlsx.full.min.js payload.js jerry.js > xlsx.jerry.js
jerryscript/build/bin/jerry xlsx.jerry.js; echo $?