{ config, pkgs, ... }:

{
  imports =
    [ # Include the results of the hardware scan.
      ./hardware-configuration.nix
      ../../modules/base.nix
      ../../modules/servers.nix
      ../../pkgs/base-packages.nix
      ../../modules/audiobookshelf.nix
      ../../modules/mailserver.nix
      # ../../modules/matrix.nix
    ];

  networking.hostName = "dalinar"; # Define your hostname.

  # Enable the X11 windowing system.
  # services.xserver.enable = true;

  # Configure keymap in X11
  # services.xserver.layout = "us";
  # services.xserver.xkbOptions = {
  #   "eurosign:e";
  #   "caps:escape" # map caps to escape.
  # };

  # Enable CUPS to print documents.
  # services.printing.enable = true;

  # Enable sound.
  # sound.enable = true;
  # hardware.pulseaudio.enable = true;

  hardware.opengl = {
   enable = true;
   extraPackages = with pkgs; [
    intel-media-driver
    vaapiIntel
    vaapiVdpau
    libvdpau-va-gl    
   ];
  };

  # Enable touchpad support (enabled default in most desktopManager).
  # services.xserver.libinput.enable = true;

  # Define a user account. Don't forget to set a password with ‘passwd’.
  users.users.chris = {
    isNormalUser = true;
    extraGroups = [ "wheel" ]; # Enable ‘sudo’ for the user.
  };

  virtualisation.docker = {
    enable = true;
    # daemon.settings = {
    #   experimental = true;
    #   ip6tables = true;
    # };
  };

  # Some programs need SUID wrappers, can be configured further or are
  # started in user sessions.
  # programs.mtr.enable = true;
  # programs.gnupg.agent = {
  #   enable = true;
  #   enableSSHSupport = true;
  # };

  services.syncthing = {
    enable = true;
    dataDir = "/storage/syncthing";
    openDefaultPorts = true;
    configDir = "/home/chris/syncthing";
    user = "chris";
    group = "users";
    guiAddress = "0.0.0.0:8384";
    overrideDevices = true;
    overrideFolders = true;
    settings = {
      devices = {
        syl = {
          id = "FPELBL2-Y6BMDOB-4TXM75K-VZV7IR3-JDMM35Z-TUEZKXX-YAPUTL6-K5SFQAN";
        };
        kaladin = {
          id = "PMB4FRV-2CAPFCQ-UFELVNI-YAQRRHE-MMMXQ4P-RXEXBZV-QEUL6QN-KZEW5AM";
        };
        shadow = {
          id = "B24VU6Z-URTMEXN-ZYKRWX7-XWSTHXD-XKX67EB-XSKMT4V-KWKGX7Q-W7DB2QV";
        };
        tablet = {
          id = "4HEXCNH-MCVBZQX-LQ735TG-P2VTJ7N-CZ5MK4P-ICZAPC7-YCXVEWV-7NILMA5";
        };
        kohlin = {
          id = "BSWKBRR-2IJBCHA-UQY7DE7-CV2U2IL-PMFQFCJ-D5ZZJMU-FPYRUPC-MCC32QQ";
        };
      };
      folders = {
        music = {
          id = "teqqy-rzvec";
          path = "/storage/syncthing/Music";
          devices = [ "syl" "kaladin" "shadow" "kohlin"];
          versioning = {
            type = "trashcan";
            params.cleanoutDays = "100";
          };
        };
        ebooks = {
          id = "wziqy-7hyv9";
          path = "/storage/syncthing/ebooks";
          devices = [ "kaladin" "tablet" "kohlin"];
          versioning = {
            type = "trashcan";
            params.cleanoutDays = "100";
          };
        };
        docs = {
          path = "/storage/syncthing/docs";
          devices = [ "syl" "kaladin" "shadow" "kohlin"];
          versioning = {
            type = "trashcan";
            params.cleanoutDays = "100";
          };
        };
        librera = {
          id = "vvtvj-osndy";
          path = "/storage/syncthing/librera";
          devices = [ "tablet" "kohlin"];
          versioning = {
            type = "trashcan";
            params.cleanoutDays = "100";
          };
        };
      };
    };
  };

  # nix-bitcoin = {
  #   generateSecrets = true;
  #   operator = {
  #     enable = false;
  #     name = "chris";
  #   };
  # };

  # List services that you want to enable:

  services.locate = {
    enable = true;
    package = pkgs.plocate;
    localuser = null;
  };

  # Enable the OpenSSH daemon.
  services.openssh.enable = true;
  services.fstrim.enable = true;
  services.logind = {
    lidSwitch = "ignore";
    lidSwitchExternalPower = "ignore";
  };

  services.monero = {
    enable = false;
    dataDir = "/storage/monero";
  };

  # services.bitcoind = {
  #   enable = false;
  #   listen = true;
  #   dataDir = "/storage/bitcoind";
  #   dbCache = 5000;
  # };

  # services.clightning = {
  #   enable = false;
  #   dataDir = "/storage/clightning";
  # };

  # services.rtl = {
  #   enable = false;
  #   dataDir = "/storage/rtl";
  #   nightTheme = true;
  #   extraCurrency = "USD";
  #   nodes.clightning.enable = true;
  # };

  # DDCLIENT
  services.ddclient = {
    enable = true;
    # configFile = /home/chris/ddclient.conf;
    domains = [
      "@"
      "nc.cochrun.xyz"
      "home.cochrun.xyz"
      "mail.cochrun.xyz"
      "jelly.cochrun.xyz"
      "rtl.cochrun.xyz"
      "sonarr.cochrun.xyz"
      "radarr.cochrun.xyz"
      "prowlarr.cochrun.xyz"
      "abs.cochrun.xyz"
      "ombi.cochrun.xyz"
      "photos.cochrun.xyz"
      "vpn.cochrun.xyz"
      "ai.cochrun.xyz"
      "vpnui.cochrun.xyz"
      "inv.cochrun.xyz"
      "tubesync.cochrun.xyz"
    ];
    passwordFile = "/home/chris/ddclientp";
    protocol = "namecheap";
    use = "cmd, cmd='${pkgs.curl}/bin/curl -s https://dynamicdns.park-your-domain.com/getip'";
    # use = "web, web=dynamicdns.park-your-domain.com/getip";
    server = "dynamicdns.park-your-domain.com";
    username = "cochrun.xyz";
    verbose = true;
    extraConfig = ''
      wildcard=YES
      ipv6=no
    '';
    #use=web, web=dynamicdns.park-your-domain.com/getip
    #protocol=namecheap
    #server=dynamicdns.park-your-domain.com
    #login=livingseedco.shop
    #password=e157e42337fc4ccd850d0a3904733f46
    #@

    #use=web, web=dynamicdns.park-your-domain.com/getip
    #protocol=namecheap
    #server=dynamicdns.park-your-domain.com
    #login=cochrun.xyz
    #password=94602c373f9f4743838bf567def2eb72
    #@,nc.cochrun.xyz,home.cochrun.xyz,mail.cochrun.xyz,jelly.cochrun.xyz


    #'';
  };

  services.nextcloud = {
    enable = false;
    home = "/storage/nextcloud";
    https = true;
    package = pkgs.nextcloud27;
    phpPackage = pkgs.php;
    hostName = "nc.cochrun.xyz";
    caching = {
      redis = true;
    };
    notify_push.enable = false;
    autoUpdateApps.enable = true;
    configureRedis = true;
    phpOptions = {
      upload_max_filesize = "1G";
      post_max_size = "1G";
      memory_limit = "2G";
      "opcache.memory_consumption" = "256";
      "opcache.jit" = "1255";
      "opcache.jit_buffer_size" = "128M";
    };
    extraOptions = {
      enabledPreviewProviders = [
        "OC\\Preview\\BMP"
        "OC\\Preview\\GIF"
        "OC\\Preview\\JPEG"
        "OC\\Preview\\Krita"
        "OC\\Preview\\MarkDown"
        "OC\\Preview\\MP3"
        "OC\\Preview\\OpenDocument"
        "OC\\Preview\\PNG"
        "OC\\Preview\\TXT"
        "OC\\Preview\\XBitmap"
        "OC\\Preview\\HEIC"
        "OC\\Preview\\Movie"
      ];
    };
    extraAppsEnable = true;
    extraApps = with config.services.nextcloud.package.packages.apps; {
      inherit contacts calendar cookbook;
    };
  };
  services.nginx.virtualHosts."localhost".listen = [ { addr = "127.0.0.1"; port = 8080; } ];

  # CADDY
  services.caddy = {
    enable = true;
    email = "chris@tfcconnection.org";
    virtualHosts = {
      "home.cochrun.xyz".extraConfig = ''
        reverse_proxy localhost:8123
      '';
    };
    virtualHosts = {
      "ai.cochrun.xyz".extraConfig = ''
        reverse_proxy localhost:11434
      '';
    };
    virtualHosts = {
      "photos.cochrun.xyz".extraConfig = ''
        reverse_proxy localhost:2283
      '';
    };
    virtualHosts = {
      "inv.cochrun.xyz".extraConfig = ''
        reverse_proxy http://127.0.0.1:3000
      '';
    };
    virtualHosts = {
      "jelly.cochrun.xyz".extraConfig = ''
        reverse_proxy localhost:8096
      '';
    };
    virtualHosts = {
      "tubesync.cochrun.xyz".extraConfig = ''
        reverse_proxy localhost:4848
      '';
    };
    virtualHosts = {
      "sonarr.cochrun.xyz".extraConfig = ''
        reverse_proxy localhost:7879
      '';
    };
    virtualHosts = {
      "radarr.cochrun.xyz".extraConfig = ''
        reverse_proxy localhost:7878
      '';
    };
    virtualHosts = {
      "192.168.1.2".extraConfig = ''
        reverse_proxy localhost:9091
      '';
    };
    virtualHosts = {
      "rtl.cochrun.xyz".extraConfig = ''
        reverse_proxy localhost:3000
      '';
    };
    virtualHosts = {
      "prowlarr.cochrun.xyz".extraConfig = ''
        reverse_proxy localhost:9696
      '';
    };
    virtualHosts = {
      "ombi.cochrun.xyz".extraConfig = ''
        reverse_proxy localhost:3579
      '';
    };
    virtualHosts = {
      "workout.cochrun.xyz".extraConfig = ''
        reverse_proxy localhost:8089
        header {
              Access-Control-Allow-Origin *
        }
      '';
    };
    virtualHosts = {
      "nc.cochrun.xyz".extraConfig = ''
        reverse_proxy localhost:8080
        encode gzip
        redir /.well-known/carddav /remote.php/dav 301
        redir /.well-known/caldav /remote.php/dav 301
        header {
              Strict-Transport-Security "max-age=15768000; includeSubDomains; reload;"
              Access-Control-Allow-Origin *
              Referrer-Policy no-referrer-when-downgrade
        }
      '';
    };
    virtualHosts = {
      "vpn.cochrun.xyz".extraConfig = ''
        encode gzip
        reverse_proxy localhost:51820
      '';
    };
    virtualHosts = {
      "vpnui.cochrun.xyz".extraConfig = ''
        encode gzip
        reverse_proxy localhost:51821
      '';
    };
  };

  systemd.services = {
    nextcloud-cron = {
      enable = true;
      serviceConfig = {
        Type = "oneshot";
        ExecStart = "${pkgs.docker}/bin/docker exec -u www-data -d nextcloud-app-1 php cron.php";
      };
    };
    nextcloud-previews = {
      enable = true;
      serviceConfig = {
        Type = "oneshot";
        ExecStart = "${pkgs.docker}/bin/docker exec -u www-data -d nextcloud-app-1 php occ preview:pre-generate";
      };
    };
    # mail-cert-renew = {
    #   enable = true;
    #   serviceConfig = {
    #     Type = "oneshot";
    #     ExecStart = with pkgs.docker "sh -c /home/chris/bin/mail-cert-renew";
    #   };
    # };
  };

  systemd.timers = {
    nextcloud-cron = {
      enable = true;
      partOf = ["nextcloud-cron.service"];
      timerConfig = {
        OnStartupSec = "2min";
        OnUnitActiveSec = "5min";
        Unit = "nextcloud-cron.service";
      };
      wantedBy = [ "timers.target" ];
    };
    nextcloud-previews = {
      enable = true;
      partOf = ["nextcloud-previews.service"];
      timerConfig = {
        OnStartupSec = "2min";
        OnUnitActiveSec = "10min";
        Unit = "nextcloud-previews.service";
      };
      wantedBy = [ "timers.target" ];
    };
  };

  # Open ports in the firewall.
  # networking.firewall.allowedTCPPorts = [ ... ];
  # networking.firewall.allowedUDPPorts = [ ... ];
  # Or disable the firewall altogether.
  networking.firewall.enable = false;
  networking.enableIPv6 = true;

  # Copy the NixOS configuration file and link it from the resulting system
  # (/run/current-system/configuration.nix). This is useful in case you
  # accidentally delete configuration.nix.
  # system.copySystemConfiguration = true;

  # This value determines the NixOS release from which the default
  # settings for stateful data, like file locations and database versions
  # on your system were taken. It‘s perfectly fine and recommended to leave
  # this value at the release version of the first install of this system.
  # Before changing this value read the documentation for this option
  # (e.g. man configuration.nix or on https://nixos.org/nixos/options.html).
  system.stateVersion = "22.05"; # Did you read the comment?

  # The nix-bitcoin release version that your config is compatible with.
  # When upgrading to a backwards-incompatible release, nix-bitcoin will display an
  # an error and provide instructions for migrating your config to the new release.
  # nix-bitcoin.configVersion = "0.0.77";
}
