{ pkgs, ... }:

let
  delugeBase = {
    environment = {
      PUID = "600";
      PGID = "100";
      TZ = "America/New_York";
      UMASK = "000";
      DEBUG = "true";
      DELUGE_DAEMON_LOG_LEVEL = "debug";
      DELUGE_WEB_LOG_LEVEL = "debug";
    };
  };

  vars = import ../vars.nix;
  #docker_path = vars.primary_docker;
  torr_path = vars.primary_torr;
  deluge_path = "${torr_path}/deluge";
  delugevpn_path = "${torr_path}/delugevpn";

  genSopsConf = file: {
    "${file}" = {
      format = "binary";
      sopsFile = ./wg/${file};
      path = "${delugevpn_path}/config/wireguard/configs/${file}";
      owner = "docker-service";
      group = "users";
      restartUnits = [ "docker-delugeVPN.service" ];
    };
  };
in
{
  virtualisation.oci-containers.containers = {
    deluge = delugeBase // {
      image = "binhex/arch-deluge";
      volumes = [
        "${deluge_path}/config:/config"
        "${deluge_path}/data/:/data"
        "/etc/localtime:/etc/localtime:ro"
      ];
      ports = [
        "8084:8112"
        "29433:29433"
      ];
    };
    delugeVPN = delugeBase // {
      image = "binhex/arch-delugevpn";
      extraOptions = [
        "--privileged=true"
        "--sysctl"
        "net.ipv4.conf.all.src_valid_mark=1"
      ];
      environment = delugeBase.environment // {
        VPN_ENABLED = "yes";
        VPN_CLIENT = "wireguard";
        VPN_PROV = "custom";
        ENABLE_PRIVOXY = "yes";
        LAN_NETWORK = "192.168.0.0/16";
        NAME_SERVERS = "194.242.2.9";
        # note, delete /config/perms.txt to force a bulk permissions update

      };
      volumes = [
        "${delugevpn_path}/config:/config"
        "${delugevpn_path}/data:/data"
        "/etc/localtime:/etc/localtime:ro"
      ];
      ports = [
        "8085:8112"
        "8119:8118"
        "39275:39275"
        "39275:39275/udp"
      ];
    };
  };

  systemd.services.docker-delugeVPN = {
    serviceConfig = {
      ExecStartPre = [
        (
          "${pkgs.bash}/bin/bash -c \"${pkgs.findutils}/bin/find ${delugevpn_path}/config/wireguard/configs "
          + "-type l -not -name wg0.conf "
          + "| ${pkgs.coreutils}/bin/shuf -n 1 "
          + "| ${pkgs.findutils}/bin/xargs -I {} cp -L {} ${delugevpn_path}/config/wireguard/wg0.conf &&"
          + "${pkgs.coreutils}/bin/chown docker-service:users ${delugevpn_path}/config/wireguard/wg0.conf &&"
          + "${pkgs.coreutils}/bin/chmod 440 ${delugevpn_path}/config/wireguard/wg0.conf\""
        )
      ];
      ExecStopPost = [ "${pkgs.coreutils}/bin/rm ${delugevpn_path}/config/wireguard/wg0.conf" ];
    };
  };

  sops.secrets =
    (genSopsConf "se-mma-wg-001.conf")
    // (genSopsConf "se-mma-wg-002.conf")
    // (genSopsConf "se-mma-wg-003.conf")
    // (genSopsConf "se-mma-wg-004.conf")
    // (genSopsConf "se-mma-wg-005.conf")
    // (genSopsConf "se-mma-wg-101.conf")
    // (genSopsConf "se-mma-wg-102.conf")
    // (genSopsConf "se-mma-wg-103.conf");
}