#include <stdint.h>
#include <sys/types.h>
#include <sys/stat.h>

#include "alloc-util.h"
#include "dropin.h"
#include "logind.h"
#include "path-util.h"

static const char *arg_dest = "/tmp";

static int read_manager_configuration(char **user_tasks_max) {
        Manager m = {};
        int r;

        manager_reset_config(&m);
        m.user_tasks_max = 0;

        r = manager_parse_config_file(&m);
        if (r < 0)
                return log_warning_errno(r, "Failed to parse logind.conf: %m");

        if (!m.user_tasks_max)
                return 0;

        *user_tasks_max = m.user_tasks_max;
        return 1;
}

int main(int argc, char *argv[]) {
        _cleanup_free_ char *p = NULL;
        char *user_tasks_max;
        int r = 0;

        if (argc > 1 && argc != 4) {
                log_error("This program takes three or no arguments.");
                return EXIT_FAILURE;
        }

        if (argc > 1)
                arg_dest = argv[1];

        log_set_target(LOG_TARGET_SAFE);
        log_parse_environment();
        log_open();

        umask(0022);

        r = read_manager_configuration(&user_tasks_max);
        if (r == 0)
                return EXIT_SUCCESS;
        if (r < 0)
                return EXIT_FAILURE;

        p = path_join(arg_dest, "user-.slice.d", "50-limits.conf");
        if (!p)
                return EXIT_FAILURE;

        log_warning("Creating %s to keep compatibility\n"
                    "Please copy the snippet in /etc/systemd/system/user-.slice.d/ and remove any uses of UserTasksMax=\n", p);

        r = write_drop_in_format(arg_dest, "user-.slice", 50, "limits",
                                 "# Automatically generated by logind-compat-tasks-max-generator\n\n"
                                 "[Slice]\nTasksMax=%s", user_tasks_max);

        return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}
