#!/bin/bash
# Checks the rules that break arm64e at runtime and that the compiler can't see. See the notes at the top of src/Islet.m.
cd "$(dirname "$0")/.."
rc=0
fail() { echo "lint: $1"; rc=1; }
# bulk edits once turned @" inside strings into NS(" and left encodings and log formats garbled
grep -nE '%NS\(|"[^"]*NS\("[^"]*$' src/Islet.m src/IsletPrefs.m && fail 'garbled format string'
grep -n 'class_addMethod' src/Islet.m src/IsletPrefs.m | grep -vE '"[vB@Q][@:{}=dqCGPoint]*"' && fail 'garbled type encoding'
# @"..." literals and class definitions are only allowed in arm64 tools and tests
grep -nE '(^|[ (\[{,=])@"|^@implementation' src/Islet.m src/IsletPrefs.m | grep -v '^[^:]*:[0-9]*: *//' && fail 'static ObjC literal or class'
# every selector a gesture targets has to exist on the runtime class
for s in $(grep -oE 'action:@selector\([a-zA-Z]+:\)' src/Islet.m | sed 's/action:@selector(\(.*\))/\1/' | sort -u); do
  grep -q "class_addMethod(c, @selector($s)" src/Islet.m || fail "gesture selector $s isn't registered"
done
# Reset to Recommended only means something if Settings shows the same defaults the tweak uses
python3 - <<'PY' || rc=1
import plistlib, re, sys
code = {}
for m in re.finditer(r'Pref(?:Bool|Num)\(NS\("(\w+)"\), ([^)]+?)\)', open('src/Islet.m').read()):
    code.setdefault(m.group(1), set()).add(m.group(2))
bad = 0
for x in plistlib.load(open('pkg/prefs/Root.plist', 'rb'))['items']:
    k = x.get('key')
    if not k or k == 'notchWidth': continue     # depends on the screen; Root.plist carries the XR's value
    v = x.get('default'); v = 'YES' if v is True else 'NO' if v is False else str(v)
    if code.get(k) != {v}: print('lint: default of', k, 'differs:', code.get(k), v); bad = 1
sys.exit(bad)
PY
exit $rc
