#!/system/bin/sh
set -eu

SRC=/data/local/tmp/magisk-env
DST=/data/adb/magisk

chmod -R 755 "$SRC"
test -x "$SRC/magisk"
test -x "$SRC/busybox"
test -f "$SRC/util_functions.sh"

rm -rf "$DST"/*
cp -af "$SRC"/. "$DST"/
chown -R 0:0 "$DST"
chmod 700 /data/adb
chmod -R 755 "$DST"

test -x "$DST/busybox"
test -f "$DST/util_functions.sh"

# Pre-authorize the local Android Debug Bridge shell before the Magisk daemon
# exists. This X11 stock build includes sqlite3, so no daemon or TV prompt is
# needed to create the exact Magisk policy row.
SQLITE=/system/bin/sqlite3
DB=/data/adb/magisk.db
test -x "$SQLITE"
"$SQLITE" "$DB" \
    "CREATE TABLE IF NOT EXISTS policies (uid INT, policy INT, until INT, logging INT, notification INT, PRIMARY KEY(uid));"
"$SQLITE" "$DB" \
    "REPLACE INTO policies (uid,policy,until,logging,notification) VALUES(2000,2,0,1,1);"
chown 0:0 "$DB"
chmod 600 "$DB"
policy=$("$SQLITE" "$DB" "SELECT policy FROM policies WHERE uid=2000;" | tr -d '\r')
test "$policy" = "2"
exit 0
