#!/bin/sh
set -eu

JBROOT=/var/jb
PATH="$JBROOT/usr/bin:$JBROOT/bin:/usr/bin:/bin:/usr/sbin:/sbin"
export PATH

APP="$JBROOT/Applications/ShutterMute26.app"
MAIN="$APP/ShutterMute26"
TWEAK="$JBROOT/usr/lib/TweakInject/ShutterMute26.dylib"
SHARE="$JBROOT/usr/share/shuttermute26"
PREFERENCES=/var/mobile/Library/Preferences/com.roxsecu.shuttermute26.plist

find_ldid() {
    for candidate in "$JBROOT/usr/bin/ldid" "$JBROOT/bin/ldid" /usr/bin/ldid; do
        if [ -x "$candidate" ]; then
            printf '%s\n' "$candidate"
            return 0
        fi
    done
    return 1
}

LDID="$(find_ldid)" || {
    echo "ShutterMute26 requires ldid to finish installation." >&2
    exit 1
}

test -x "$MAIN"
test -x "$TWEAK"

"$LDID" -S"$SHARE/ShutterMute26.entitlements" "$MAIN"
"$LDID" -S "$TWEAK"

APP_ENTITLEMENTS="$($LDID -e "$MAIN" 2>/dev/null)"
printf '%s\n' "$APP_ENTITLEMENTS" | grep -q '<key>platform-application</key>'
if printf '%s\n' "$APP_ENTITLEMENTS" | grep -Eq 'no-sandbox|no-container|absolute-path.read-write|task_for_pid-allow|system-task-ports|get-task-allow'; then
    echo "ShutterMute26 app contains an unexpected entitlement." >&2
    exit 1
fi

chown -R root:wheel "$APP" "$TWEAK" "$JBROOT/usr/lib/TweakInject/ShutterMute26.plist" "$SHARE"
chmod 0755 "$APP" "$MAIN" "$TWEAK"
chmod 0644 "$JBROOT/usr/lib/TweakInject/ShutterMute26.plist" "$SHARE/ShutterMute26.entitlements"

if [ ! -f "$PREFERENCES" ]; then
    cp "$SHARE/default-preferences.plist" "$PREFERENCES"
fi
chown mobile:mobile "$PREFERENCES"
chmod 0600 "$PREFERENCES"

add_trustcache() {
    binary="$1"
    cdhashes="$($LDID -h "$binary" 2>&1 | sed -n 's/.*CDHash=\([0-9a-fA-F]*\).*/\1/p')"
    [ -n "$cdhashes" ] || return 1

    for cdhash in $cdhashes; do
        if [ -x "$JBROOT/basebin/jbctl" ]; then
            "$JBROOT/basebin/jbctl" trustcache add "$cdhash" >/dev/null 2>&1
        elif [ -x /var/jb/basebin/jbctl ]; then
            /var/jb/basebin/jbctl trustcache add "$cdhash" >/dev/null 2>&1
        else
            echo "ShutterMute26 could not find a supported trustcache tool." >&2
            return 1
        fi
    done
}

add_trustcache "$MAIN"
add_trustcache "$TWEAK"

if [ -x "$JBROOT/usr/bin/uicache" ]; then
    "$JBROOT/usr/bin/uicache" -p "$APP"
elif command -v uicache >/dev/null 2>&1; then
    uicache -p "$APP"
fi

killall -9 Camera >/dev/null 2>&1 || true
exit 0
