{ pkgs, lib, config, userName, ... }:
let
  inherit (lib) listToAttrs nameValuePair;
  
  xmobar = import ./xmobar pkgs.haskellPackages;
  cfg = config.home-manager.users.${userName};

  autossh-socks-script = pkgs.writeScript "autossh" ''
    #!${pkgs.zsh}/bin/zsh -xe

    host="''${1%:*}"
    port="''${1#*:}"

    typeset -a cmd
    cmd=()

    if [[ -n "''${SSHPASS_SECRET}" ]]; then
      cmd+=(${pkgs.sshpassSecret}/bin/sshpass-secret)
      cmd+=("''${(@s/:/)SSHPASS_SECRET}")
      cmd+=(--)
    fi

    cmd+=(${pkgs.openssh}/bin/ssh -vN -D localhost:''${port} "''${host}")

    ( exec -a "''${cmd[1]}" -- ''${cmd} ) &
    pid=$!

    newpid=""
    i=200
    while ! newpid=$(${pkgs.lsof}/bin/lsof -Pi @localhost:"''${port}" -sTCP:LISTEN -t); do
      if ! kill -0 "''${pid}"; then
        wait "''${pid}"
        exit $?
      fi
      [[ "''${i}" -gt 0 ]] || exit 1
      i=$((''${i} - 1))
      ${pkgs.coreutils}/bin/sleep 0.1
    done

    ${pkgs.systemd}/bin/systemd-notify --ready

    wait "''${pid}" "''${newpid}"
  '';
in {
  services = {
    sync-keepass = {
      Service = {
        Type = "oneshot";
        WorkingDirectory = "~";
        ExecStart = toString (pkgs.writers.writePython3 "sync-keepass" {
          libraries = with pkgs.python3Packages; [ dateutil ];
        } ''
          import json
          import subprocess
          from os.path import (expanduser, getmtime, dirname)
          from datetime import datetime
          from dateutil.tz import tzlocal
          from dateutil.parser import isoparse
          from sys import stderr


          remote_fs = 'surtr'
          remote_file = 'store.kdbx'
          target_file = expanduser('~/store.kdbx')
          meta_file = expanduser('~/.store.kdbx.json')

          upload_time = None
          our_last_upload_time = None
          mod_time = None


          def get_upload_time():
              upload_time = None
              with subprocess.Popen(['rclone', 'lsjson', f'{remote_fs}:{dirname(remote_file)}'], stdout=subprocess.PIPE) as proc:  # noqa: E501
                  for file in json.load(proc.stdout):
                      if file['Path'] != remote_file:
                          continue
                      else:
                          upload_time = isoparse(file['ModTime'])
                          break
              return upload_time


          def do_upload():
              print('Uploading', file=stderr)
              subprocess.run(['rclone', 'copy', '-I', target_file, f'{remote_fs}:{dirname(remote_file)}'], check=True)  # noqa: E501
              upload_time = get_upload_time()
              with open(meta_file, 'w') as file:
                  json.dump({'our_last_upload_time': upload_time.isoformat()}, file)


          def do_download():
              print('Downloading', file=stderr)
              subprocess.run(['rclone', 'copy', '-I', f'{remote_fs}:{remote_file}', dirname(target_file)], check=True)  # noqa: E501


          upload_time = get_upload_time()

          try:
              with open(meta_file, 'r') as file:
                  file_content = json.load(file)
                  our_last_upload_time = isoparse(file_content['our_last_upload_time'])  # noqa: E501
          except FileNotFoundError:
              pass

          try:
              mod_time = datetime.fromtimestamp(getmtime(target_file)).replace(tzinfo=tzlocal())  # noqa: E501
          except FileNotFoundError:
              pass

          if upload_time is None or (mod_time is not None and mod_time > upload_time):  # noqa: E501
              do_upload()
          elif upload_time is not None and (mod_time is None or upload_time > mod_time) and (our_last_upload_time is None or upload_time > our_last_upload_time):  # noqa: E501
              do_download()
        '');
        Environment = [ "RCLONE_PASSWORD_COMMAND=\"${pkgs.coreutils}/bin/cat ${config.sops.secrets.gkleen-rclone.path}\"" "PATH=${pkgs.rclone}/bin" ];
      };
    };
    emacs = {
      Unit = {
        After = ["graphical-session-pre.target"];
      };
    };
    taffybar = {
      Service = {
        Environment = with pkgs; "PATH=${worktime}/bin:${systemd}/bin";
      };
    };
    dunst = {
      Service = {
        Restart = "always";
      };
      Install = {
        WantedBy = ["graphical-session.target"];
      };
    };
    xiccd = {
      Service = {
        Type = "simple";
        WorkingDirectory = "~";
        ExecStart = "${pkgs.xiccd}/bin/xiccd";
        Restart = "always";
      };
    };
    "autossh-socks@proxy.mathw0h:8119" = {
      Service = {
        Type = "notify";
        NotifyAccess = "all";
        WorkingDirectory = "~";
        Restart = "always";
        RestartSec = "23s";
        ExecStart = "${autossh-socks-script} \"%I\"";
        Environment = [ "SSHPASS_SECRET=gkleen@mathw0g.math.lmu.de" ];
      };
      Unit = {
        StopWhenUnneeded = true;
        StartLimitInterval = "180s";
        StartLimitBurst = 7;
      };
    };
    "autossh-socks@proxy.vidhar:8121" = {
      Service = {
        Type = "notify";
        NotifyAccess = "all";
        WorkingDirectory = "~";
        Restart = "always";
        RestartSec = "2s";
        ExecStart = "${autossh-socks-script} \"%I\"";
      };
      Unit = {
        StopWhenUnneeded = true;
      };
    };
  } // listToAttrs (map ({host, port}: nameValuePair "proxy-to-autossh-socks@${toString port}" {
      Unit = {
        Requires = ["autossh-socks@${host}:${toString (port + 1)}.service" "proxy-to-autossh-socks@${toString port}.socket"];
        After = ["autossh-socks@${host}:${toString (port + 1)}.service" "proxy-to-autossh-socks@${toString port}.socket"];
      };
      Service = {
        ExecStart = "${pkgs.systemd}/lib/systemd/systemd-socket-proxyd --exit-idle-time=10s localhost:${toString (port + 1)}";
      };
  }) [{ host = "proxy.mathw0h"; port = 8118; } { host = "proxy.vidhar"; port = 8120; }]);
  sockets = listToAttrs (map (port: nameValuePair "proxy-to-autossh-socks@${toString port}" {
    Socket = {
      ListenStream = "%I";
    };
    Install = {
      WantedBy = ["default.target"];
    };
  }) [8118 8120]);
  timers = {
    sync-keepass = {
      Timer = {
        OnActiveSec = "1m";
        OnUnitActiveSec = "1m";
      };

      Install = {
        WantedBy = ["default.target"];
      };
    };
  };
  targets = {
    graphical-session = {
      Unit = {
        BindsTo = ["default.target"];
        After = ["basic.target"];
      };
    };
  };
}