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

with lib;

let

  # name of the program
  # -------------------
  program = "slack";

  tarBin = "${pkgs.gnutar}/bin/tar";

  # command that will be jailed
  # ---------------------------
  command = "${pkgs.slack}/bin/slack";

  desktopFile = let
    name = program;
    comment = "Chat Programm";
  in pkgs.writeTextFile {
    name = "${name}.desktop";
    destination = "/share/applications/${name}.desktop";
    text = ''
      [Desktop Entry]
      Categories=Application;Utility;
      Comment=${comment}
      Encoding=UTF-8
      Exec=${bin}/bin/${name}
      Icon=gnome-lockscreen
      Name=${name}
      Terminal=false
      Type=Application
    '';
  };

  # the script
  # ----------
  bin = let
    backupFile = "${cfg.homeBackup}.tar.lzma";
    rolloutFile = "${cfg.home}.tar.lzma";
    lockFile = "${cfg.home}-lock";
  in pkgs.writeShellScriptBin "${program}" ''
    # set -x
    if [[ ! -e ${lockFile} ]]
    then
      # rollout backup
      if [[ -e ${backupFile} ]]
      then
        cp ${backupFile} ${rolloutFile}
        sudo -u ${program} ${tarBin} xf ${rolloutFile} --directory ${cfg.home}
        rm ${rolloutFile}
        touch ${lockFile}
      fi
    fi

    sudo -u ${program} ${command}
  '';

  backupScript = pkgs.writeShellScriptBin "${program}-backup" ''
    sudo -u ${program} \
      ${tarBin} \
      --exclude=.cache \
      --exclude=".config/**/*Cache*" \
      --exclude-cache-all \
      --exclude=Downloads \
      --create \
      --verbos \
      --lzma \
      --file ${cfg.home}.tar.lzma \
      --directory ${cfg.home} \
      .

    cp ${cfg.home}.tar.lzma ${cfg.homeBackup}.tar.lzma
  '';

  cfg = config.programs.custom.slack;

in {

  options.programs.custom.slack = {
    enable = mkEnableOption "install slack";

    homeBackup = mkOption {
      type = with types; nullOr string;
      description = ''
        folder where to backup
      '';
    };

    # todo : make sure the folder /home/sudoers belongs to mainUser
    home = mkOption {
      type = with types; string;
      default = "/home/sudoers/slack";
      description = ''
        home folder of this
      '';
    };

  };

  config = mkIf cfg.enable {

    security.sudo.extraConfig = ''
      ${config.users.users.mainUser.name} ALL=(${program}) NOPASSWD: ALL
    '';

    # create users
    users.users."${program}" = {
      home = cfg.home;
      createHome = true;
      # initialPassword = "${program}";
      shell = pkgs.bashInteractive;
      isNormalUser = true;
      group = "users";
      # enable video usage
      extraGroups = [ "video" "audio" ];
    };

    environment.systemPackages = [ bin backupScript desktopFile ];
  };
}