#!/usr/bin/python3
"""
Configure chrony to set system time from the network

Configures `chrony` to set the system time from the given `timeservers`.

Modifies /etc/chrony.conf, removing all "server" or "pool" lines and adding
a "server" line for each server listed in `timeservers`.
"""


import sys
import re

import osbuild.api


SCHEMA = """
"additionalProperties": false,
"required": ["timeservers"],
"properties": {
  "timeservers": {
    "type": "array",
    "items": { "type": "string" },
    "description": "Array of NTP server addresses"
  }
}
"""
DELETE_LINE_REGEX = re.compile(r"(server|pool) ")


def main(tree, options):
    timeservers = options["timeservers"]

    with open(f"{tree}/etc/chrony.conf") as f:
        chrony_conf = f.read()

    # split to lines and remove ones starting with server and pool
    lines = chrony_conf.split('\n')
    lines = [line for line in lines if not DELETE_LINE_REGEX.match(line)]

    # prepend new server lines
    newlines = [f"server {server} iburst" for server in timeservers]
    newlines += lines

    new_chrony_conf = "\n".join(newlines)

    with open(f"{tree}/etc/chrony.conf", "w") as f:
        f.write(new_chrony_conf)

    return 0


if __name__ == '__main__':
    args = osbuild.api.arguments()
    r = main(args["tree"], args["options"])
    sys.exit(r)
