#!/usr/bin/env python3
import os
import re
import subprocess
import sys

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
IMG_PATH = os.path.join(SCRIPT_DIR, "..", "public", "pinecraft_backup.img")

if not os.path.exists(IMG_PATH):
    print(f"[!] Image not found: {IMG_PATH}", file=sys.stderr)
    sys.exit(1)

# Extract printable strings from the raw disk image
result = subprocess.run(
    ["strings", IMG_PATH],
    capture_output=True, text=True, timeout=120
)
lines = result.stdout.split("\n")

# Flag 1: IP address of attacker from server.log
flag1_found = False
for line in lines:
    m = re.search(r"Unauthorized access from (\d+\.\d+\.\d+\.\d+)", line)
    if m:
        ip = m.group(1)
        print(f"Flag 1: vsosh{{{ip}}}")
        flag1_found = True
        break

if not flag1_found:
    print("[!] Flag 1 not found — no 'Unauthorized access from' line", file=sys.stderr)

# Flag 2: Secret password from deleted admin_backup.txt
flag2_found = False
for line in lines:
    m = re.search(r"secret_password:\s*(\S+)", line)
    if m:
        password = m.group(1)
        print(f"Flag 2: vsosh{{{password}}}")
        flag2_found = True
        break

if not flag2_found:
    print("[!] Flag 2 not found — no 'secret_password:' line in strings output", file=sys.stderr)
