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

let
  stateDir = "/var/lib/dnsmasq";
  blocklist = "${stateDir}/dnsmasq.blacklist.txt";

in {
  # PostgreSQL daily backups
  services.postgresqlBackup = {
    enable = true;
    backupAll = true;
    location = "/vault/backups/zion/databases";
    startAt = "*-*-* 05:15:00";
  };

  # Fetch hosts-blocklists daily
  # FIXME Download the list if the file doesn't exist the first time
  systemd.services.download-dns-blocklist = {
    description = "Download hosts-blocklists";
    wantedBy = [ "default.target" ];
    path = with pkgs; [ curl coreutils ];
    script = ''
      curl -L https://github.com/notracking/hosts-blocklists/raw/master/dnsmasq/dnsmasq.blacklist.txt -o ${blocklist}
      sed "/cainiao/d" -i ${blocklist}
    '';
    serviceConfig.Type = "oneshot";
    postStop = ''
      chown -R dnsmasq ${stateDir}
    '';
    requiredBy = [ "dnsmasq.service" ];
    startAt = "02:00:00";
  };

  # Enable SATA HAT fans
  systemd.services.sata-hat = {
    description = "Enable software support for SATA Hat";
    wantedBy = [ "default.target" ];
    script = ''
      ${pkgs.bash}/bin/bash -c "/home/coolneng/system/scripts/SATA-hat.sh on"
    '';
    serviceConfig = {
      Type = "oneshot";
      RemainAfterExit = "yes";
      ExecStop = ''
        ${pkgs.bash}/bin/bash -c "/home/coolneng/system/scripts/SATA-hat.sh off"
      '';
    };
  };

  # Idle HDDs when not used
  systemd.services.hd-idle = {
    description = "Idle HDDs when not in use";
    wantedBy = [ "default.target" ];
    path = with pkgs; [ hd-idle ];
    script = ''
      ${pkgs.hd-idle}/bin/hd-idle -i 0 -a ata-ST1000LM035-1RK172_WKPAKV85 -i 600
      -a ata-HGST_HTS721010A9E630_JR100X6P3UJG5E -i 600
    '';
    serviceConfig.Type = "simple";
    requires = [ "sata-hat.service" ];
    after = [ "vault.mount" ];
  };

  # Push zion changes to git daily
  systemd.user.services.zion-push = {
    description = "Push zion changes to git";
    wantedBy = [ "default.target" ];
    path = with pkgs; [ git ];
    script = ''
      ${pkgs.git}/bin/git -C /home/coolneng/system pull
      ${pkgs.git}/bin/git -C /home/coolneng/system push
    '';
    serviceConfig.Type = "oneshot";
    startAt = "07:00:00";
    after = [ "network-online.target" ];
  };
}