#!/usr/bin/env python3
"""Read-only S7/TIA network preflight. No probes, device writes or data deletion."""
import argparse
import ipaddress
import json
import platform
import re
import shutil
import subprocess
import sys
from pathlib import Path


def command(args):
    try:
        result = subprocess.run(args, capture_output=True, text=True, timeout=5, check=False)
        return {'exitCode': result.returncode, 'stdout': result.stdout.strip(), 'stderr': result.stderr.strip()}
    except (OSError, subprocess.TimeoutExpired) as error:
        return {'exitCode': None, 'stdout': '', 'stderr': str(error)}


def ip_json(args):
    result = command(['ip', '-j', *args])
    if result['exitCode'] != 0:
        return [], result['stderr'] or 'ip command failed'
    try:
        return json.loads(result['stdout']), None
    except json.JSONDecodeError:
        return [], 'invalid ip JSON output'


def same_subnet(addresses, plc):
    return any(plc in ipaddress.ip_interface(f"{address['local']}/{address['prefixlen']}").network
               for address in addresses if address.get('family') == 'inet')


def collect(interface, plc, helper):
    links, link_error = ip_json(['link', 'show', 'dev', interface])
    addresses, address_error = ip_json(['address', 'show', 'dev', interface])
    link = links[0] if links else {}
    ipv4 = [item for entry in addresses for item in entry.get('addr_info', []) if item.get('family') == 'inet']
    capability = command(['getcap', str(helper)]) if shutil.which('getcap') else {'exitCode': None, 'stdout': '', 'stderr': 'getcap unavailable'}
    warnings = [value for value in (link_error, address_error) if value]
    if not link or 'UP' not in link.get('flags', []):
        warnings.append('Selected interface is absent or administratively down.')
    if link.get('link_type') != 'ether':
        warnings.append('DCP requires an Ethernet interface; this interface is not confirmed Ethernet.')
    if not ipv4:
        warnings.append('No IPv4 address available for S7/TIA online access.')
    if not helper.is_file():
        warnings.append('DCP helper not found at the supplied installation path.')
    route, route_error = ip_json(['route', 'get', str(plc)]) if plc else ([], None)
    if route_error:
        warnings.append(route_error)
    if plc and route and route[0].get('dev') != interface:
        warnings.append('PLC route uses another interface; review the route before testing.')
    if plc and not same_subnet(ipv4, plc):
        warnings.append('PLC is outside every IPv4 subnet on the selected interface.')
    # Neither a local IP/subnet match nor CAP_NET_RAW proves physical L2 access.
    return {
        'schema': 1, 'mode': 'read-only-preflight', 'plcModel': 'S7-1215',
        'interface': interface, 'link': link, 'ipv4': ipv4,
        'plcIp': str(plc) if plc else None, 'routeLookup': route,
        'sameIpv4Subnet': same_subnet(ipv4, plc) if plc else None,
        'helperExists': helper.is_file(), 'helperCapabilities': capability,
        'dcpLayer2Reachability': 'notTested', 'tiaOnline': 'notTested',
        'warnings': warnings,
        'nextSteps': ['Provide an actual PLC IP and the TIA computer/version.',
                      'Confirm the gateway NIC and PLC share the required physical L2 segment; VM NAT is insufficient evidence.',
                      'Use authenticated read-only DCP Identify, then separately verify S7/TIA online operation.'],
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--interface', required=True)
    parser.add_argument('--plc-ip', help='Optional actual IPv4 address; route lookup only, no packets sent')
    parser.add_argument('--helper', type=Path, default=Path('/usr/bin/bdiiot-dcp-bridge'))
    parser.add_argument('--output', type=Path, help='Optional new JSON file; refuses to overwrite')
    args = parser.parse_args()
    if platform.system() != 'Linux':
        parser.error('Linux only')
    if not re.fullmatch(r'[A-Za-z0-9_.:-]{1,15}', args.interface):
        parser.error('Invalid Linux interface name')
    try:
        plc = ipaddress.IPv4Address(args.plc_ip) if args.plc_ip else None
    except ipaddress.AddressValueError:
        parser.error('PLC address must be IPv4')
    if plc and (plc.is_multicast or plc.is_unspecified or plc.is_loopback or
                plc == ipaddress.IPv4Address('255.255.255.255')):
        parser.error('PLC address must be a unicast non-loopback address')
    result = json.dumps(collect(args.interface, plc, args.helper), ensure_ascii=False, indent=2)
    if args.output:
        with args.output.open('x', encoding='utf-8') as stream:
            stream.write(result + '\n')
    else:
        print(result)


if __name__ == '__main__':
    main()
