#!/bin/bash
# WebKitCompat postinst script

echo "[WebKitCompat] Running post-installation..."

# Fix tweak dylib and plist permissions
chmod 755 /var/jb/Library/MobileSubstrate/DynamicLibraries/WebKitCompat.dylib 2>/dev/null
chmod 644 /var/jb/Library/MobileSubstrate/DynamicLibraries/WebKitCompat.plist 2>/dev/null

# Fix preference bundle permissions
chmod 755 /var/jb/Library/PreferenceBundles/WebKitCompatPrefs.bundle 2>/dev/null
chmod 755 /var/jb/Library/PreferenceBundles/WebKitCompatPrefs.bundle/WebKitCompatPrefs 2>/dev/null
chmod 644 /var/jb/Library/PreferenceBundles/WebKitCompatPrefs.bundle/Root.plist 2>/dev/null
chmod 644 /var/jb/Library/PreferenceLoader/Preferences/WebKitCompatPrefs.plist 2>/dev/null

# CRITICAL: Kill app and WebKit processes so they reload with the new tweak
# These processes cache the dylib and won't pick up changes without being killed
echo "[WebKitCompat] Killing myChevrolet and WebKit processes to reload tweak..."

# Kill myChevrolet app - MUST be killed so tweak loads in app process
killall -9 myChevrolet 2>/dev/null && echo "[WebKitCompat] Killed myChevrolet" || true
killall -9 MyChevrolet 2>/dev/null || true

# Kill SafariViewService - this is where WKWebView lives for OAuth
killall -9 SafariViewService 2>/dev/null && echo "[WebKitCompat] Killed SafariViewService" || true

# Kill WebContent processes
killall -9 com.apple.WebKit.WebContent 2>/dev/null && echo "[WebKitCompat] Killed WebContent" || true
killall -9 WebContent 2>/dev/null || true

# Kill Networking process - handles NSURLProtocol
killall -9 com.apple.WebKit.Networking 2>/dev/null && echo "[WebKitCompat] Killed Networking" || true
killall -9 Networking 2>/dev/null || true

# Kill GPU process just in case
killall -9 com.apple.WebKit.GPU 2>/dev/null || true

# Clear the log file for fresh debugging
LOG_FILE="/var/jb/var/mobile/Library/Preferences/com.local.webkitcompat.log"
if [ -f "$LOG_FILE" ]; then
    echo "" > "$LOG_FILE"
    echo "[WebKitCompat] Cleared log file"
fi

echo "[WebKitCompat] Installation complete!"
echo "[WebKitCompat] The tweak will load when you next open myChevrolet."
echo "[WebKitCompat] If login page is still blank, try: sbreload"

exit 0
