#!/usr/bin/python3

import json
import subprocess

      
machines = json.loads(subprocess.check_output("maas root nodes read", shell=True))
for machine in machines:
    system_id = machine["system_id"]
    hostname = machine["hostname"]
    print("Checking interfaces for machine {} with ID {}".format(hostname, system_id))
    interfaces = json.loads(subprocess.check_output("maas root interfaces read {}".format(system_id), shell=True))
    for interface in interfaces:
        link_id = None
        links = interface["links"]
        if len(links) == 2:
            for link in links:
                if link["mode"] == "auto":
                    link_id = link["id"]
                    nic_id = interface["id"]
                    print("Removing link_id {} for NIC {} for machine {} with name {}".format(link_id, nic_id, system_id, hostname))
                    subprocess.check_call("maas root interface unlink-subnet {} {} id={}".format(system_id, nic_id, link_id), shell=True)
                    break