#!/bin/env python3
import sys
from os import listdir
from os.path import isfile, join
from json import loads
from debian import parse_debian
from freebsd import parse_freebsd
from freebox import parse_freebox
from jinja2 import Environment, FileSystemLoader

def find_os(content):
    version = content.split("###### VERSION ######")[-1]
    jcontent = {}
    try:
        jcontent = loads(version)
    except:
        osystem = [line.split("=")[-1] for line in version.splitlines() if line.startswith("ID=")]
        if osystem:
            return osystem[0]
    if "ID" in jcontent:
        return jcontent["ID"]
    return "freebox"


def main():
    mypath = "../oxidized/"

    onlyfiles = [mypath + f for f in listdir(mypath) if isfile(join(mypath, f))]
    env = Environment(loader = FileSystemLoader('../template'))

    for file in onlyfiles:
        print("opening {} file ...".format(file.split("/")[-1]))
        with open(file,"r") as f:
            content = f.read()
        current_os = find_os(content)
        if "freebsd" in current_os:
            infos = parse_freebsd(content)
            infos["extend_exists"] = False
            template = env.get_template('freebsd.rst.j2')
        elif "debian" in current_os:
            infos = parse_debian(content)
            infos["extend_exists"] = False
            template = env.get_template('debian.rst.j2')
        else:
            infos = parse_freebox(content)
            infos = {
                "hostname":"Freebox",
                "os":{"NAME":"FreeboxOS","VERSION":"None"},
            }
            infos["extend_exists"] = False
        output = template.render(**infos)
        with open("../source/devices/{host}.rst".format(host=infos["hostname"].replace("\n","")), "w") as f:
            f.write(output)

if __name__ == "__main__":
    main()