#!/system/bin/sh

dir=$(realpath "${0%/*}")
cd "$dir" || exit 1

if [ "false" != "true" ] && [ ! -r /data/local/tmp/daemon.apk ]; then
    (
        isa=$(getprop ro.product.cpu.abi)
        isa=${isa%%-*}
        [ "$isa" = "armeabi" ] && isa=arm
        case "$isa" in *64) bits=64 ;; *) bits=32 ;; esac
        for art_bin in /apex/com.android.art/bin /apex/com.android.runtime/bin /system/bin; do
            [ -x "$art_bin/dexoptanalyzer" ] && break
        done
        "$art_bin/dexoptanalyzer" --dex-file="$dir/daemon.apk" --isa="$isa" \
            --compiler-filter=speed '--class-loader-context=PCL[]'
        case "$?" in
            [1-7]) # ART's recompile results, not analyzer errors (101+).
                compiler="$art_bin/dex2oat$bits"
                [ -x "$compiler" ] || compiler="$art_bin/dex2oat"
                umask 022
                mkdir -p "$dir/oat/$isa" &&
                    "$compiler" --dex-file="$dir/daemon.apk" \
                        --oat-file="$dir/oat/$isa/daemon.odex" --instruction-set="$isa" \
                        --compiler-filter=speed '--class-loader-context=PCL[]'
                ;;
        esac
    )
fi

log -p i -t "LSPosed" "starting lspd $*"
./lspd "$@" >/dev/null 2>&1 &
PID=$!
log -p i -t "LSPosed" "started lspd $PID"
wait $PID
rc=$?

if [ $rc -ne 0 ]; then
    log -p e -t "LSPosed" "lspd $PID exited unexpectedly, code=$rc"
    mkdir -p /data/adb/lspd/log
    logcat -b all -f "/data/adb/lspd/log/daemon-$PID-crash-$(date -Iseconds).log" -t 100000 -v uid
fi
