#!/usr/bin/python3
# -*- mode: sh; indent-tabs-mode: nil; sh-basic-offset: 4; -*-
# vim: et sts=4 sw=4

#  SPDX-License-Identifier: LGPL-2.1+
#
#  Copyright © 2021 Collabora Ltd.
#  Copyright © 2021 Valve Corporation.
#
#  This file is part of steamos-customizations.
#
#  steamos-customizations is free software; you can redistribute it and/or
#  modify it under the terms of the GNU Lesser General Public License as
#  published by the Free Software Foundation; either version 2.1 of the License,
#  or (at your option) any later version.

import os

def unit_name_escape(dev):
    unit = dev.strip("/")
    unit = unit.replace("-", "\\x2d")
    unit = unit.replace("/", "-")

    return unit

def add_mount(what, where, type, options, passno, source):
    bind = "bind" in options
    unit = unit_name_escape(where) + ".mount"
    directory = "/run/systemd/generator/"
    with open(directory + unit, "w") as f:
        f.write("# Automatically generated by steamos-steamlibtab-generator\n")

        f.write("\n[Unit]\n")
        f.write("Documentation=man:fstab(5)\n")
        f.write("SourcePath=%s\n" % source)
        if not bind:
            if (passno != 0):
                f.write("Wants=systemd-fsck@%s.service\n" % unit_name_escape(what))
                f.write("After=systemd-fsck@%s.service\n" % unit_name_escape(what))
            f.write("After=blockdev@%s.target\n" % unit_name_escape(what))

        f.write("\n[Mount]\n")
        f.write("Where=%s\n" % where)
        f.write("What=%s\n" % what)
        if (type and type != "auto"):
            f.write("Type=%s\n" % type)
        # FIXME: systemd fails to mount if options contains a space even if it
        # espaced (i.e. \040).
        # run-steam-0.mount: Failed to run 'mount' task: Invalid argument
        # run-steam-0.mount: Failed with result 'resources'.
        # Failed to mount /run/steam/0.
        f.write("Options=%s\n" % ",".join([ i for i in options if not i.startswith("x-steamos.steamlib") ]))

        try:
            os.mkdir(directory + "local-fs.target.wants/", 0o755)
        except:
            pass

        try:
            os.symlink("../" + unit, directory + "local-fs.target.wants/" + unit)
        except:
            pass

    steamlib = [ i for i in options if i.startswith("x-steamos.steamlib") ]
    if len(steamlib) > 0:
        steamlib = steamlib[0].removeprefix("x-steamos.steamlib=")
    if steamlib:
        steamlib = steamlib.replace("\\040", " ")
        what = where + steamlib
        where = where.replace("/run/steam/", "/run/steamlib/")
        type = None
        options = ["nofail", "bind"]
        passno = 0
        add_mount(what, where, type, options, passno, source)

def parse_steamlibtab(source):
    with open(source, "r") as f:
        for line in f:
            words = line.split()
            if len(words) < 4 or words[0][0] == '#':
                continue

            what = words[0]
            if (what.startswith("PARTUUID=")):
                what = what.replace("PARTUUID=", "/dev/disk/by-partuuid/")
            elif (what.startswith("UUID=")):
                what = what.replace("UUID=", "/dev/disk/by-uuid/")
            where = words[1]
            type = words[2]
            options = words[3].split(",")
            passno = words[5]

            add_mount(what, where, type, options, passno, source)

parse_steamlibtab("/etc/steamlibtab")
