{ config, lib, pkgs, ... }:

with lib;

let
  cfg = config.services;
  mkInitialDatabases = servicename: if (cfg."${servicename}".enable && (cfg."${servicename}".database.type == "mysql")) then
    let 
      password = (fileContents "${config.machine.secretPath}/${servicename}_db");
      cfg = config.services."${servicename}".database;
    in {
      name = cfg.name;
      schema = pkgs.writeText "${cfg.name}.sql" ''
        create user if not exists ${cfg.user}@'localhost' identified by ${password};
        grant all privileges on ${cfg.name}.* to ${cfg.user}@'localhost' identified by ${password};
      '';
    } else { name = ""; };
in mkIf (elem "mariaDB" config.machine.services) {
  services.mysql = {
    enable = true;
    package = pkgs.mariadb;
    initialDatabases = (map mkInitialDatabases [ "mailman3" "gitea" ]);
  };
}