#!/usr/bin/python3
"""
Create /etc/fstab entries for filesystems

Create /etc/fstab entries for the given `filesystems`.

Each filesystem item must have at least `uuid` or `label` and
a `path` (mount point).

This stage replaces /etc/fstab, removing any existing entries.
"""


import sys

import osbuild.api


SCHEMA = """
"additionalProperties": false,
"required": ["filesystems"],
"properties": {
  "filesystems": {
    "type": "array",
    "description": "array of filesystem objects",
    "items": {
      "type": "object",
      "oneOf": [{
        "required": ["uuid", "path"]
      }, {
        "required": ["label", "path"]
      }],
      "properties": {
        "uuid": {
          "description": "Filesystem UUID",
          "type": "string"
        },
        "label": {
          "description": "Filesystem label",
          "type": "string"
        },
        "path": {
          "description": "Filesystem mountpoint",
          "type": "string"
        },
        "vfs_type": {
          "description": "Filesystem type",
          "type": "string",
          "default": "none"
        },
        "options": {
          "description": "Filesystem options (comma-separated)",
          "type": "string",
          "default": "defaults"
        },
        "freq": {
          "description": "dump(8) period in days",
          "type": "number",
          "default": 0
        },
        "passno": {
          "description": "pass number on parallel fsck(8)",
          "type": "number",
          "default": 0
        }
      }
    }
  }
}
"""


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

    with open(f"{tree}/etc/fstab", "w") as f:
        for filesystem in filesystems:
            uuid = filesystem.get("uuid")
            path = filesystem["path"]
            label = filesystem.get("label")
            vfs_type = filesystem.get("vfs_type", "none")
            options = filesystem.get("options", "defaults")
            freq = filesystem.get("freq", 0)
            passno = filesystem.get("passno", 0)

            if uuid:
                fs_spec = f"UUID={uuid}"
            elif label:
                fs_spec = f"LABEL={label}"
            else:
                raise ValueError("Need 'uuid' or 'label'")

            f.write(f"{fs_spec}\t{path}\t{vfs_type}\t{options}\t{freq}\t{passno}\n")


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