#!/usr/bin/env python3
"""Proposal for the m5: refresh only the family-games pf table. Never loads/enables PF."""
import argparse
import subprocess
import sys

from _lan import home_lan_addresses, resolve_ipv4


def refresh(host, dry=False, resolver=resolve_ipv4, runner=subprocess.run):
    try:
        addresses = home_lan_addresses(resolver(host))
        if not addresses:
            raise ValueError('no 192.168.86.x client address')
    except (OSError, ValueError, subprocess.SubprocessError) as exc:
        # Keep the last good table: one missed mDNS answer must not cut the kids off the hub.
        # A real address change is picked up by the next successful lookup (60 s).
        print('lan-proxy-pf-refresh: resolution failed; table left as it was: ' + str(exc), file=sys.stderr)
        return 1
    if dry:
        print('\n'.join(addresses))
    else:
        result = runner(['/sbin/pfctl', '-a', 'com.apple/ricardo.family-games',
                         '-t', 'family_games_clients', '-T', 'replace', '-f', '-'],
                        input=''.join(address + '\n' for address in addresses),
                        capture_output=True, text=True, timeout=5)
        if result.returncode:
            raise OSError('pf table update failed: ' + result.stderr.strip())
        print('family_games_clients=' + ','.join(addresses), flush=True)
    return 0


def main():
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument('--host', default='Ricardos-Mac-mini.local')
    ap.add_argument('--dry', action='store_true', help='resolve and print only; never invoke pfctl')
    args = ap.parse_args()
    try:
        return refresh(args.host, args.dry)
    except (OSError, subprocess.SubprocessError) as exc:
        print('lan-proxy-pf-refresh: ' + str(exc), file=sys.stderr)
        return 1


if __name__ == '__main__':
    raise SystemExit(main())
