#!/usr/bin/env python3
"""MariaDB component drill: dump the MISP database, restore it into a NEW database
(misp_restore_drill) and compare row counts and the training event. Never touches the
live `misp` database, never prints passwords (they stay inside the db container env).
Run in lab/ on the host: python3 backup-drill.py. Keeps the dump and the restored DB."""
import subprocess
import uuid
from datetime import datetime, timezone

NS = uuid.UUID('6f1c9a52-7d0b-4f36-9a51-5ec7001ab000')
CASE = str(uuid.uuid5(NS, 'sectools-lab-phishing-case'))
STAMP = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')
DUMP = f'/backups/misp-{STAMP}.sql.gz'


def db(script):
    cmd = ['docker', 'compose', 'exec', '-T', 'db', 'sh', '-c', script]
    return subprocess.run(cmd, check=True, capture_output=True, text=True).stdout.strip()


ROOT = 'mariadb -uroot -p"$MYSQL_ROOT_PASSWORD" -N -B'
db(f'mariadb-dump -uroot -p"$MYSQL_ROOT_PASSWORD" --single-transaction --routines --triggers misp | gzip > {DUMP}')
size = int(db(f'stat -c %s {DUMP}'))
assert size > 10_000, size
print(f'PASS dump: {DUMP} ({size} bytes, --single-transaction)')

db(f'{ROOT} -e "DROP DATABASE IF EXISTS misp_restore_drill; CREATE DATABASE misp_restore_drill"')
db(f'gunzip -c {DUMP} | {ROOT} misp_restore_drill')
print('PASS restore: dump loaded into new database misp_restore_drill')

checks = {}
for table in ('events', 'attributes', 'objects', 'tags', 'organisations', 'correlation_values'):
    live = db(f'{ROOT} -e "SELECT COUNT(*) FROM misp.{table}"')
    restored = db(f'{ROOT} -e "SELECT COUNT(*) FROM misp_restore_drill.{table}"')
    assert live == restored, (table, live, restored)
    checks[table] = int(live)
print('PASS row counts match: ' + ', '.join(f'{t}={n}' for t, n in checks.items()))
info = db(f"""{ROOT} -e "SELECT info FROM misp_restore_drill.events WHERE uuid='{CASE}'" """)
assert info.startswith('SecTools Lab'), info
print(f'PASS restored training event found by UUID: {CASE[:8]}…')
