#!/usr/bin/python3
# This script is used to transform the output from the show ip ospf commands and order
# them to match the ietf-ospf YANG model. For example, interfaces is ordered under
# area but FRR has areas in interfaces.
#
# This makes the parsing for the operational parts of YANG model more easy
#

import json
import subprocess

iface_out=subprocess.check_output("vtysh -c 'show ip ospf interface json'", shell=True)
ospf_out=subprocess.check_output("vtysh -c 'show ip ospf json'", shell=True)
neighbor_out=subprocess.check_output("vtysh -c 'show ip ospf neighbor detail json'", shell=True)
interfaces=json.loads(iface_out)
ospf=json.loads(ospf_out)
neighbors=json.loads(neighbor_out)

for ifname,iface in interfaces["interfaces"].items():
    iface["name"] = ifname
    iface["neighbors"] = []
    for nbrAddress,nbrDatas in neighbors["neighbors"].items():
        for nbrData in nbrDatas:
            nbrIfname=nbrData["ifaceName"].split(":")[0]
            if nbrIfname != ifname:
                continue
            nbrData["neighborIp"] = nbrAddress
            iface["neighbors"].append(nbrData)
    for area_id in ospf["areas"]:
        if(iface["area"] != area_id):
           continue
        if(not ospf["areas"][area_id].get("interfaces", None)):
            ospf["areas"][area_id]["interfaces"] = []
        ospf["areas"][area_id]["interfaces"].append(iface)
print(json.dumps(ospf))

