#!/usr/bin/env bash
# Cleanup revision: 1.1 (reviewed legacy cg.* state files)
# Remove the GPUOS mstate/.lm chain evidenced in this investigation.
# Does not claim to remove every unknown modification of a third-party image.
set -Eeuo pipefail
umask 077
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/hive/bin:/hive/sbin
[[ $EUID == 0 ]] || { echo 'Use sudo bash deletegpuos.sh'; exit 1; }
case "${1:---check}" in --check|--apply) ;; *) echo 'Usage: bash deletegpuos.sh --check|--apply'; exit 1;; esac
for c in python3 flock bash miner; do command -v "$c" >/dev/null || { echo "Missing: $c"; exit 1; }; done
exec 9>/run/deletegpuos-cleanup.lock
flock -n 9 || { echo 'Another cleanup is running'; exit 1; }
export GPUOS_CLEAN_MODE="${1:---check}"
python3 - <<'PY'
import os, re, sys, stat, json, time, signal, hashlib, tempfile, shutil, subprocess
from pathlib import Path

APPLY = os.environ['GPUOS_CLEAN_MODE'] == '--apply'
TARGETS = ['/hive/bin/miner-run', '/hive/bin/custom', '/hive/miners/custom/custom']
STATE = Path('/hive-config/.mstate')
CRON = Path('/etc/cron.d/mstate')
LAUNCH = Path('/var/lib/.lm/onezerominer')
BIN = Path('/hive/miners/custom/onezerominer/onezerominer')

def fail(msg): raise RuntimeError(msg)
def regular(p):
    if p.is_symlink(): fail('Refusing symlink: '+str(p))
    if p.exists() and not p.is_file(): fail('Not a regular file: '+str(p))
def digest(p):
    h=hashlib.sha256()
    with open(p,'rb') as f:
        for b in iter(lambda:f.read(1024*1024),b''): h.update(b)
    return h.hexdigest()
def check_legacy_cg(directory):
    # State only: never execute, decode or follow URLs from these files.
    names={'cg.rel','cg.sha','cg.show','cg.result','cg.urls','cg.fb'}
    for name in names:
        p=directory/name
        regular(p)
        if p.exists() and p.stat().st_size>65536:
            fail('Unexpectedly large legacy state file: '+str(p))
    return names
def clean_launcher(text):
    # Preserve the outer fallback verbatim, not an invented Hive launcher.
    pattern=r'(?ms)^# lm-if\n.*?^# lm-end(?=\n|$)'
    def unwrap(m):
        b=m.group(0)
        if b.count('# lm-if')!=1: fail('Nested launcher patch; manual review required')
        marker='\nelse\n'
        i=b.rfind(marker)
        if i<0 or not b.endswith('\nfi\n# lm-end'):
            fail('Unknown lm block; manual review required')
        stock=b[i+len(marker):-len('\nfi\n# lm-end')]
        if 'h-run.sh' not in stock or re.search(r'\.mstate|/var/lib/\.lm',stock):
            fail('Unsafe or unknown fallback')
        return stock
    out=re.sub(pattern,unwrap,text)
    if re.search(r'# lm-(?:if|end)|launcher\.mark|/var/lib/\.lm|\.mstate/launcher',out):
        fail('Unrecognized launcher patch remains')
    return out
def snapshot():
    result={}
    for p in Path('/proc').iterdir():
        if not p.name.isdigit(): continue
        try:
            raw=(p/'stat').read_text(); fields=raw[raw.rfind(')')+2:].split()
            args=(p/'cmdline').read_bytes().split(b'\0')
            result[int(p.name)]=(fields[19],int(fields[1]),fields[0],args)
        except (OSError,IndexError): pass
    return result
def stop_mstate():
    snap=snapshot()
    roots={pid for pid,v in snap.items() if
           b'/hive-config/.mstate/mstate' in v[3] and pid!=os.getpid()}
    targets=set(roots)
    while True:
        new={pid for pid,v in snap.items() if v[1] in targets}
        if new<=targets: break
        targets |= new
    if not targets: return
    print('Stopping mstate process tree:',sorted(targets),flush=True)
    # pidfd prevents a recycled PID from being signalled.
    handles={}
    try:
        for pid in targets:
            try:
                fd=os.pidfd_open(pid)
                now=snapshot().get(pid)
                if now and now[0]==snap[pid][0]: handles[pid]=fd
                else: os.close(fd)
            except ProcessLookupError: pass
        for fd in handles.values():
            try: signal.pidfd_send_signal(fd,signal.SIGTERM)
            except ProcessLookupError: pass
        time.sleep(2)
        for fd in handles.values():
            try: signal.pidfd_send_signal(fd,signal.SIGKILL)
            except ProcessLookupError: pass
    finally:
        for fd in handles.values(): os.close(fd)
def miners():
    found=[]
    for pid,v in snapshot().items():
        if v[2]=='Z': continue
        p=Path('/proc')/str(pid)
        try:
            exe=os.readlink(p/'exe'); cwd=os.readlink(p/'cwd')
            if 'onezerominer' in exe and cwd==str(BIN.parent):
                found.append((pid,exe,digest(p/'exe')))
        except OSError: pass
    return found

try:
    if not hasattr(os,'pidfd_open') or not hasattr(signal,'pidfd_send_signal'):
        fail('Python with pidfd support is required; no cleanup performed')
    prepared={}
    for name in TARGETS:
        p=Path(name); regular(p)
        if not p.exists(): continue
        original=p.read_bytes(); clean=clean_launcher(original.decode()).encode()
        subprocess.run(['bash','-n'],input=clean,check=True)
        if original!=clean: prepared[name]=(original,clean)
    if not Path(TARGETS[0]).is_file(): fail('Hive miner-run missing')
    regular(CRON)
    if CRON.exists():
        for line in CRON.read_text().splitlines():
            if line.strip() and not line.lstrip().startswith('#') and '/hive-config/.mstate/mstate' not in line:
                fail('cron.d/mstate contains unrelated entries; review required')
    for p in [STATE,LAUNCH]:
        if p.is_symlink(): fail('Refusing symlink directory: '+str(p))
        if p.exists() and not p.is_dir(): fail('Unexpected directory type: '+str(p))
    if STATE.exists():
        legacy=check_legacy_cg(STATE)
        unexpected={p.name for p in STATE.iterdir()}-({'mstate','m','launcher.mark'}|legacy)
        if unexpected: fail('Unknown .mstate contents: '+repr(unexpected))
        s=STATE/'mstate'; regular(s)
        if s.exists():
            text=s.read_text()
            if not all(x in text for x in ['COMPONENT=onezerominer','mp_st_report','/worker/api?method=mstate']):
                fail('Different mstate implementation; review required')
    if LAUNCH.exists():
        for p in LAUNCH.iterdir():
            if p.name not in {'1.8.5','1.8.6'} or p.is_symlink() or not p.is_dir():
                fail('Unknown launcher version: '+str(p))
            if {q.name for q in p.iterdir()}-{'key','h-run.sh'}:
                fail('Unknown launcher files: '+str(p))
            for q in p.iterdir(): regular(q)
            run=p/'h-run.sh'
            if run.exists() and 'https://gpuos.org/downloads/onezerominer/' not in run.read_text():
                fail('Unrecognized launcher: '+str(run))
    regular(BIN)
    if not BIN.is_file(): fail('Expected OneZeroMiner binary missing')
    disk_hash=digest(BIN)
    current=miners()
    affected=any('/memfd:' in e or h!=disk_hash for _,e,h in current)
    paths=[p for p in [CRON,STATE,LAUNCH] if p.exists()]
    print('Launcher files to repair:',list(prepared),flush=True)
    print('Paths to remove from active locations:',[str(p) for p in paths],flush=True)
    print('Current miner executable checks:',current,flush=True)
    print('PRESERVED: official connection, wallets, OC, native patch services, grub, libnvidia-api.so.1',flush=True)
    if not APPLY:
        print('CHECK_ONLY: no changes. Use --apply after reviewing this report.')
        sys.exit(0)
    if not prepared and not paths and not affected:
        print('NO_CHANGE: known chain absent; no miner restart needed.')
        sys.exit(0)
    if not current: fail('No running target miner; refusing to change mining state automatically')
    backup=Path(tempfile.mkdtemp(prefix='gpuos-removal.',dir='/root'))
    print('BACKUP='+str(backup),flush=True)
    def save(p):
        dest=backup/str(p).lstrip('/'); dest.parent.mkdir(parents=True,exist_ok=True)
        if p.is_dir(): shutil.copytree(p,dest,symlinks=True)
        else: shutil.copy2(p,dest)
    for name in prepared: save(Path(name))
    for p in paths: save(p)
    # Every active file is backed up before any cleanup mutation.
    if CRON.exists(): CRON.unlink()
    stop_mstate()
    # Recheck launchers against the prepared originals before mutation.
    for name,(original,_) in prepared.items():
        if Path(name).read_bytes()!=original: fail('Launcher changed during preflight: '+name)
    restart_needed=False
    try:
        restart_needed=True
        subprocess.run(['miner','stop'],check=True,timeout=90)
        for _ in range(15):
            if not miners(): break
            time.sleep(1)
        if miners(): fail('Miner processes survived miner stop; refusing forced kill')
        for name,(_,clean) in prepared.items():
            p=Path(name); fd,temp=tempfile.mkstemp(prefix='.gpuos-clean.',dir=p.parent)
            try:
                with os.fdopen(fd,'wb') as f: f.write(clean); f.flush(); os.fsync(f.fileno())
                shutil.copystat(p,temp)
                st=p.stat(); os.chown(temp,st.st_uid,st.st_gid)
                os.replace(temp,p)
            finally:
                if os.path.exists(temp): os.unlink(temp)
        for p in [LAUNCH,STATE]:
            if p.exists(): shutil.rmtree(p)
        try: Path('/var/lib/.lm').rmdir()
        except OSError: pass
    finally:
        if restart_needed:
            print('Restarting miner...',flush=True)
            subprocess.run(['miner','start'],check=True,timeout=90)
    passed=False
    for _ in range(30):
        time.sleep(2)
        found=miners()
        if found and all(e==str(BIN) and h==disk_hash for _,e,h in found):
            passed=True; break
    print('POST_CHECK:',miners(),flush=True)
    if not passed: fail('Miner executable verification not passed within 60s; inspect miner/API')
    if any(p.exists() for p in [CRON,STATE,LAUNCH]): fail('Removed entry reappeared; another installer exists')
    for name in TARGETS:
        p=Path(name)
        if p.exists() and re.search(r'launcher\.mark|/var/lib/\.lm',p.read_text()):
            fail('Launcher entry remains: '+name)
    print('SUCCESS_KNOWN_CHAIN_REMOVED: running executable matches disk.')
    print('Confirm accepted shares in Hive. This is not a full OS trust audit.')
except Exception as e:
    print('ERROR:',e,flush=True)
    print('Cleanup may be partial if a BACKUP path was printed. Inspect log; no compromised files auto-restored.',flush=True)
    sys.exit(1)
PY
