#!/usr/bin/env python3

from swiplserver import PrologMQI, PrologThread
import yaml
import os

def to_ansible(kind, hosts):
  for host, o in hosts.items():
      print(f"host={host}")
      os.makedirs(f"host_vars/{host}", exist_ok=True)
      with open(f"host_vars/{host}/{kind}.yaml", "w") as f:
          f.write(yaml.dump(o))

with PrologMQI() as mqi:
    with mqi.create_thread() as p:
        result = p.query("consult(main), main.")
        print(result)

        result = p.query("bgp:bird_config(BirdDict)")
        r = result[0]["BirdDict"]
        print(yaml.dump(r))
        to_ansible("bgp", r)

        hosts = {}
        result = p.query("firewall:fw_rule(Host, Attrs).")
#        print(yaml.dump(result))
        for r in result:
            host = r["Host"]
            if host not in hosts:
                hosts[host] = h = {}
                h["firewall_rules"] = rules = []
            rules.append(r["Attrs"])
            
        to_ansible("firewall", hosts)