#!/usr/bin/python

import subprocess
import re

out = subprocess.getoutput('incus ls --all-projects -f compact -c 4n|grep eth0')
container = []
new_block = "### START INCUS ###\n\n"
for line in out.split("\n"):
    items = line.strip().split(None)
    container.append({'ip': items[0], 'container': 'incus.'+items[2]})
for con in container:
    new_block += f"{con['ip']}\t{con['container']}\n"
new_block += "\n### ENDE INCUS ###\n"
print(new_block)

### Text Ersetzen
with open("/etc/hosts", encoding="utf-8") as f:
    text = f.read()

# pattern = r"### START ###[\w\W]*### ENDE ###"
pattern = r"### START INCUS ###[\w\W]*### ENDE INCUS ###"

if re.match(pattern, text, flags=re.MULTILINE|re.UNICODE):
    print("ersetzen")
    text = re.sub(pattern, new_block, text, flags=re.MULTILINE|re.UNICODE)
else:
    text += "\n" + new_block + "\n"

with open("/etc/hosts", "w", encoding="utf-8") as f:
    f.write(text)
