{ lib, pkgs, ... }:

let
  pname = "nordvpn";
  version = "3.20.1";

  nordVPNBase = pkgs.stdenv.mkDerivation rec {
    inherit pname version;

    src = pkgs.fetchurl {
      url = "https://repo.nordvpn.com/deb/nordvpn/debian/pool/main/n/nordvpn/nordvpn_${version}_amd64.deb";
      hash = "sha256-RJoI3G4Tr3272CZ/lI9HEfKXdwuwPzWlrOKm9taIjuU=";
    };

    buildInputs = with pkgs; [
      libxml2
      libidn2
    ];
    nativeBuildInputs = with pkgs; [
      dpkg
      autoPatchelfHook
      stdenv.cc.cc.lib
      libnl
      libcap_ng
    ];

    dontConfigure = true;
    dontBuild = true;

    unpackPhase = ''
      runHook preUnpack
      dpkg --extract $src .
      runHook postUnpack
    '';

    installPhase = ''
      runHook preInstall
      mkdir -p $out
      mv usr/* $out/
      mv var/ $out/
      mv etc/ $out/
      runHook postInstall
    '';
  };

  nordVPNfhs = pkgs.buildFHSEnvChroot {
    name = "nordvpnd";
    runScript = "nordvpnd";

    targetPkgs =
      pkgs: with pkgs; [
        nordVPNBase
        sysctl
        iptables
        iproute2
        procps
        cacert
        libxml2
        libidn2
        zlib
        wireguard-tools
      ];
  };

  preScript = pkgs.writeShellScript "nordvpn-start" ''
    mkdir -m 700 -p /var/lib/nordvpn;
    if [ -z "$(ls -A /var/lib/nordvpn)" ]; then
      cp -r ${nordVPNBase}/var/lib/nordvpn/* /var/lib/nordvpn;
    fi
  '';
in
pkgs.stdenv.mkDerivation rec {
  inherit pname version;

  dontUnpack = true;
  dontConfigure = true;
  dontBuild = true;

  installPhase = ''
    runHook preInstall
    mkdir -p $out/bin $out/share
    ln -s ${nordVPNBase}/bin/nordvpn $out/bin
    ln -s ${nordVPNfhs}/bin/nordvpnd $out/bin
    ln -s ${nordVPNBase}/share/* $out/share/
    ln -s ${nordVPNBase}/var $out/
    runHook postInstall
  '';

  meta = with lib; {
    description = "CLI client for NordVPN";
    homepage = "https://www.nordvpn.com";
    license = licenses.unfreeRedistributable;
    maintainers = with maintainers; [ dr460nf1r3 ];
    platforms = [ "x86_64-linux" ];
  };
}
