#!/usr/bin/python3
"""
Create group accounts

Create group accounts, optionally assigning them static GIDs.

Runs `groupadd` from the buildhost to create the groups listed in `groups`.
If no `gid` is given, `groupadd` will choose one.

If the specified group name or GID is already in use, this stage will fail.
"""


import subprocess
import sys

import osbuild.api


SCHEMA = """
"additionalProperties": false,
"properties": {
  "groups": {
    "type": "object",
    "description": "Keys are group names, values are objects with group info",
    "propertyNames": {
      "pattern": "^[A-Za-z0-9_][A-Za-z0-9_-]{0,31}$"
    },
    "additionalProperties": {
      "type": "object",
      "properties": {
        "gid": {
          "type": "number",
          "description": "GID for this group"
        }
      }
    }
  }
}
"""


def groupadd(root, name, gid=None):
    arguments = []
    if gid:
        arguments += ["--gid", str(gid)]

    subprocess.run(["groupadd", "--root", root, *arguments, name], check=True)


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

    for name, group_options in groups.items():
        gid = group_options.get("gid")

        groupadd(tree, name, gid)

    return 0


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