#!/usr/bin/env python3
"""Equivalent of the user's ThirteenServer setup.bat for Batocera 41.

Only a marked block in /etc/hosts is managed. No game files, certificates,
firewall rules, credentials or existing DNS settings are changed.
"""
import pathlib
import os
import shutil
import socket
import sys
import time

ROOT = pathlib.Path(os.environ.get('PES13_ROOT', '/userdata'))
BASE = ROOT / 'system/pes2013/online'
HOSTS = pathlib.Path(os.environ.get('PES13_HOSTS', '/etc/hosts'))
IP = '95.214.55.111'
DOMAINS = (
    'ntl.konamionline.com',
    'info.service.konamionline.com',
    'pes13-pc-gate.winning-eleven.net',
    'pes13pcstun-e.winning-eleven.net',
    'resic06.konami',
)
BEGIN = '# BEGIN PES2013 THIRTEENSERVER (managed)'
END = '# END PES2013 THIRTEENSERVER (managed)'
PREFIX = pathlib.Path(os.environ.get('WINEPREFIX', str(ROOT / 'system/wine-bottles/windows/PES 2013.wsquashfs')))


def split_block(text):
    if BEGIN not in text and END not in text:
        return text
    lines = text.splitlines(keepends=True)
    starts = [i for i, line in enumerate(lines) if line.rstrip('\r\n') == BEGIN]
    ends = [i for i, line in enumerate(lines) if line.rstrip('\r\n') == END]
    if len(starts) != 1 or len(ends) != 1 or starts[0] >= ends[0]:
        raise RuntimeError('Bloque hosts ambiguo: no se modifica')
    return ''.join(lines[:starts[0]] + lines[ends[0] + 1:])


def write_hosts(before, after):
    if before == after:
        return
    backup = BASE / 'respaldos'
    backup.mkdir(parents=True, exist_ok=True)
    shutil.copy2(HOSTS, backup / ('hosts.' + str(time.time_ns())))
    # Keep the existing inode, permissions and any mount association.
    with HOSTS.open('w', encoding='utf-8', newline='') as stream:
        stream.write(after)


def start():
    before = HOSTS.read_text()
    clean = split_block(before)
    for line in clean.splitlines():
        fields = line.split('#', 1)[0].lower().split()
        if len(fields) > 1 and set(fields[1:]).intersection(DOMAINS):
            raise RuntimeError('Existe una entrada PES fuera del bloque gestionado: ' + line)
    separator = '' if not clean or clean.endswith('\n') else '\n'
    block = BEGIN + '\n' + ''.join(f'{IP}  {name}\n' for name in DOMAINS) + END + '\n'
    write_hosts(before, clean + separator + block)
    # Same %ProgramData% destination as setup.bat, inside the existing game prefix.
    if (PREFIX / 'drive_c').is_dir():
        download = PREFIX / 'drive_c/ProgramData/KONAMI/Pro Evolution Soccer 2013/download'
        download.mkdir(parents=True, exist_ok=True)
        print('Carpeta de datos:', download)
    print('ThirteenServer activado:', IP)


def stop():
    before = HOSTS.read_text()
    write_hosts(before, split_block(before))
    print('Retirado solamente el bloque de ThirteenServer')


def status():
    text = HOSTS.read_text()
    active = BEGIN in text and END in text
    print('Bloque hosts:', 'activo' if active else 'inactivo')
    if not active:
        return 1
    ok = True
    for name in DOMAINS:
        resolved = sorted({row[4][0] for row in socket.getaddrinfo(name, None, socket.AF_INET)})
        print(name, '=>', ', '.join(resolved))
        ok = ok and resolved == [IP]
    return 0 if ok else 1


if __name__ == '__main__':
    action = sys.argv[1] if len(sys.argv) == 2 else ''
    if action == 'start':
        start()
    elif action == 'stop':
        stop()
    elif action == 'status':
        sys.exit(status())
    else:
        sys.exit('Uso: thirteen.py start|stop|status')
