#!/usr/bin/env python3
# spear.cx: In DB-Threads antworten (schaltet Hidden Content frei), Thread neu laden
import subprocess, re, time, os, json, html as H

COOKIE = os.path.expanduser('~/.hermes/cache/scratch/mode_leaks/spear_cookies.txt')
UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
DIR = os.path.expanduser('~/krypto-angriff/spear_unlocked')
os.makedirs(DIR, exist_ok=True)

TIDS = [308, 309, 2686, 576, 306, 2257, 3220, 112, 147]

def curl(args, timeout=90):
    p = subprocess.run(['curl', '-s', '-m', str(timeout), '-L', '-A', UA, '-b', COOKIE] + args,
                      capture_output=True, text=True)
    return p.stdout

def get(url):
    return curl([url])

def post(url, data):
    args = [url, '-X', 'POST']
    for k, v in data.items():
        args += ['-F', f'{k}={v}']
    return curl(args)

results = {}
for tid in TIDS:
    # 1) Reply-Form laden
    page = get(f'https://spear.cx/newreply.php?tid={tid}')
    mk = re.search(r'my_post_key\s*=\s*["\']([a-f0-9]+)["\']', page)
    if not mk:
        print(tid, 'NO POST KEY', len(page), flush=True)
        results[tid] = 'nokey'
        continue
    key = mk.group(1)
    subject = re.search(r'name="subject"[^>]*value="([^"]*)"', page)
    subj = subject.group(1) if subject else 'Re'
    subj = subj.replace('&amp;', '&')
    msg = 'Thanks for sharing, appreciate it.'
    # 2) Reply absenden
    r = post(f'https://spear.cx/newreply.php?tid={tid}&processed=1', {
        'my_post_key': key,
        'subject': subj,
        'message': msg,
        'postoptions[signature]': '1',
        'action': 'do_newreply',
        'posthash': re.search(r'name="posthash"\s+value="([^"]*)"', page).group(1) if re.search(r'name="posthash"\s+value="([^"]*)"', page) else '',
        'submit': 'Post Reply',
    })
    ok = 'Thank you' in r or 'redirect' in r.lower() or len(r) > 2000
    print(tid, 'replied', ok, flush=True)
    results[tid] = 'replied' if ok else 'fail:' + r[:100]
    time.sleep(4)
    # 3) Thread neu laden
    t = get(f'https://spear.cx/showthread.php?tid={tid}')
    open(f'{DIR}/thread_{tid}.html', 'w').write(t)
    hid = t.count('You must reply to this thread to view')
    print(tid, 'refetched', len(t), 'hidden_left:', hid, flush=True)
    time.sleep(3)

json.dump(results, open(DIR + '/reply_status.json', 'w'), indent=1)
print('DONE', flush=True)
