{ inputs, config, pkgs, ... }:
let
  notify_script = (pkgs.writers.writePython3Bin "telegram-notify.py" {
    libraries = [ pkgs.python3Packages.python-telegram-bot ];
  } ''
    import telegram
    import asyncio
    import sys
    import subprocess


    async def run():
        text = subprocess.check_output(
            ["journalctl", "--user", "-u", sys.argv[1], "-b"]
        ).decode("utf-8")

        with open("/home/server/mail.log", "a") as f:
            f.write("===========================================")
            f.write(text)

        bot = telegram.Bot(token="381718873:AAElFmI2BDjumCehhWicuksE0vutrPSkoGA")
        chat_id = 125754925
        await bot.send_message(
            chat_id, "Mallorea encountered an error in the service: " + sys.argv[1]
        )

        await bot.send_message(chat_id, text)


    if __name__ == "__main__":
        loop = asyncio.get_event_loop()
        loop.run_until_complete(asyncio.wait([loop.create_task(run())]))
        loop.close()
  '');
  mkTimer = name: cfg: {
    Install.WantedBy = [ "timers.target" ];
    Timer = {
      Persistent = true;
      OnCalendar = cfg.when;
      Unit = "${name}.service";
    };
  };
  mkService = name: cfg: {
    Unit.Description = name;
    Unit.OnFailure = "status_notify@%n.service";
    Install = { WantedBy = [ "default.target" ]; };
    Service = { ExecStart = cfg.script; };
  };
  scripts = {
    disk_check = {
      when = "*-*-* *:00:00";
      script = toString (pkgs.writeShellScript "script" ''
        REPORT_EMAIL=email@thomasave.be
        ZPOOL_STATUS=$(zpool status -x)
        if [ "$ZPOOL_STATUS" = "all pools are healthy" ] || [ "$ZPOOL_STATUS" = "no pools available" ]
        then
            printf 0 > /var/db/zpool.status
        else
            if [ "$(cat /var/db/zpool.status)" -eq 0 ]
            then
                zpool status | mail -s "ZPOOL NOT HEALTHY" $REPORT_EMAIL
                printf 1 > /var/db/zpool.status
            fi
        fi
      '');
    };
    vdirsyncer = {
      when = "*:0/15";
      script = toString (pkgs.writeShellScript "script" ''
        ${pkgs.vdirsyncer}/bin/vdirsyncer sync imec/pair
      '');
    };
    mbsync = {
      when = "*-*-* 00:00:00";
      script = toString (pkgs.writeShellScript "script" ''
        BASEDIR=/home/server/Containers/mbsync
        # python3 $BASEDIR/config/oauth2/mutt_oauth2.py $BASEDIR/data/oauth2/credentials.json
        docker exec --user "1000:1000" mbsync-container /home/user/.config/mbsync/run.sh -a
        ${pkgs.notmuch}/bin/notmuch new
      '');
    };
    sync_vault = {
      when = "*-*-* 02:00:00";
      script = toString (pkgs.writeShellScript "script" ''
        source $HOME/.secrets/Backup/env.sh
        for _ in {1..2}; do
            OUTPUT=$(echo "$ZFS_PASSPHRASE" | ssh 10.4.0.1 zfs load-key Vault/Thomas/Encrypted  2>&1);
            if [ "$OUTPUT" == "Key load error: Key already loaded for 'Vault/Thomas/Encrypted'." ]; then
                echo "Key successfully loaded, starting syncoid"
                syncoid --no-privilege-elevation --no-sync-snap tank/Storage/Thomas/Workspace 10.4.0.1:Vault/Thomas/Encrypted/Storage/Workspace
                syncoid --no-privilege-elevation --no-sync-snap tank/Storage/Thomas 10.4.0.1:Vault/Thomas/Encrypted/Storage/T
                syncoid --no-privilege-elevation --no-sync-snap tank/Storage/Niels 10.4.0.1:Vault/Thomas/Encrypted/Storage/N
                syncoid --no-privilege-elevation --no-sync-snap tank/Storage/Yolande 10.4.0.1:Vault/Thomas/Encrypted/Storage/Y
                syncoid --no-privilege-elevation --no-sync-snap tank/Containers 10.4.0.1:Vault/Thomas/Encrypted/Containers
                ssh 10.4.0.1 zfs unload-key Vault/Thomas/Encrypted
                ${pkgs.curl}/bin/curl https://uptime.thomasave.be/api/push/s39pIIrB0R
                exit 0
            fi
        done

        echo "Found output instead: $OUTPUT"
        echo "Failed to load key: $OUTPUT" | sendmail
        exit 1
      '');
    };
    backup = {
      when = "*-*-* 04:00:00";
      script = toString (pkgs.writeShellScript "script" ''
        ${./scripts/files/backup.sh}
        ${pkgs.curl}/bin/curl https://uptime.thomasave.be/api/push/R6iJcWqGp0
      '');
    };
  };
in {
  home.username = "server";
  home.homeDirectory = "/home/server";
  nix = {
    package = pkgs.nix;
    settings.use-xdg-base-directories = true;
  };

  xdg.enable = true;
  # home.profileDirectory = "${config.xdg.stateHome}/nix/profile";
  imports = [ (import ./common.nix { inherit inputs config pkgs; }) ./ssh ];
  programs.ssh.matchBlocks."*".identityFile = "/home/server/.secrets/SSH/Mallorea/id_ed25519";

  home.sessionVariables = {
    NIX_PATH = "${config.xdg.stateHome}/nix/profiles/channels/";
    LANG = "en_US.UTF-8";
    XDG_RUNTIME_DIR = "/run/user/$(id -u)";
  };

  systemd.user.services = pkgs.lib.mapAttrs mkService scripts
    // (pkgs.lib.mapAttrs mkService {
      "status_notify@" = {
        script = "${notify_script}/bin/telegram-notify.py %i";
      };
    });
  systemd.user.timers = pkgs.lib.mapAttrs mkTimer scripts;

  # Don't forget to enable these timers! Or reboot, after which it should also be activated automatically
  # systemctl --user enable --now backup.timer
  # systemctl --user enable --now sync_vault.timer
  # systemctl --user enable --now mbsync.timer
  # systemctl --user enable --now vdirsyncer.timer
  # systemctl --user enable --now disk_check.timer
}