#!/usr/bin/env python3
"""Launch SvT via adb, attach Frida, and keep ServerMessenger.sessionId
non-empty so boot proceeds past the analytics-ready gate. Attach-based
(more robust than spawn in background)."""
import json, sys, time, subprocess, frida

ADB = "/opt/android-sdk/platform-tools/adb"
A = json.load(open("/root/ants/sid_addr.json"))

JS = r"""
var GSID=%d;
function ins(){
  var m=Process.findModuleByName("libil2cpp.so"); if(!m) return false;
  var b=m.base;
  var e=m.findExportByName?m.findExportByName("il2cpp_string_new")
                         :Module.getGlobalExportByName("il2cpp_string_new");
  var strnew=new NativeFunction(e,'pointer',['pointer']);
  send({t:"info",m:"hooked sessionId"});
  Interceptor.attach(b.add(GSID),{onLeave:function(rv){
    var empty=true;
    try{ if(!rv.isNull()){ empty=(rv.add(8).readS32()<=0); } }catch(e){}
    if(empty){ rv.replace(strnew(Memory.allocUtf8String("revived-session-0001"))); }
  }});
  return true;
}
if(!ins()){ var iv=setInterval(function(){ if(ins()) clearInterval(iv); },150); }
""" % A["get_sessionId"]

dev = frida.get_device_manager().add_remote_device("127.0.0.1:27042")

subprocess.run([ADB, "shell", "am", "force-stop", "se.foglo.svt"])
subprocess.run([ADB, "shell", "monkey", "-p", "se.foglo.svt", "-c",
                "android.intent.category.LAUNCHER", "1"],
               stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

pid = None
for _ in range(60):
    out = subprocess.run([ADB,"shell","pidof","se.foglo.svt"],capture_output=True,text=True).stdout.strip()
    if out:
        pid = int(out.split()[0]); break
    time.sleep(0.25)
if pid is None:
    print("could not find process"); sys.exit(1)
print("attached to pid", pid)

session = dev.attach(pid)
script = session.create_script(JS)
script.on("message", lambda m, d: print("[msg]", m.get("payload") if m["type"] == "send" else m))
script.load()

# auto-accept the Terms-of-Use popup after boot
def accept():
    time.sleep(float(sys.argv[2]) if len(sys.argv) > 2 else 20)
    subprocess.run([ADB, "shell", "input", "tap", "1077", "748"])
    print("[tap] accepted TOS")
import threading
threading.Thread(target=accept, daemon=True).start()

time.sleep(int(sys.argv[1]) if len(sys.argv) > 1 else 600)
