{ nixpkgs ? import ./nixpkgs.nix {} }:

let
  inherit (nixpkgs {}) pkgs;
  haskellPackages = import ./stackage.nix { inherit nixpkgs; };

  drv = haskellPackages.callPackage ./uniworx.nix {};

  postgresSchema = pkgs.writeText "schema.sql" ''
    CREATE USER uniworx WITH SUPERUSER;
    CREATE DATABASE uniworx_test;
    GRANT ALL ON DATABASE uniworx_test TO uniworx;
    CREATE DATABASE uniworx;
    GRANT ALL ON DATABASE uniworx TO uniworx;
  '';

  postgresHba = pkgs.writeText "hba_file" ''
    local all all trust
  '';

  override = oldAttrs: {
    nativeBuildInputs = oldAttrs.nativeBuildInputs ++ (with pkgs; [ nodejs-8_x postgresql pgadmin openldap ]) ++ (with haskellPackages; [ stack yesod-bin hlint cabal-install ]);
    shellHook = ''
      export PROMPT_INFO="${oldAttrs.name}"

      if [[ -z "$PGHOST" ]]; then
        set -xe

        pgDir=$(mktemp -d)
        pgSockDir=$(mktemp -d)
        pgLogFile=$(mktemp)
        initdb --no-locale -D ''${pgDir}
        pg_ctl start -D ''${pgDir} -l ''${pgLogFile} -w -o "-k ''${pgSockDir} -c listen_addresses=''' -c hba_file='${postgresHba}' -c unix_socket_permissions=0700"
        export PGHOST=''${pgSockDir} PGLOG=''${pgLogFile}
        psql -f ${postgresSchema} postgres
        printf "Postgres logfile is %s\nPostgres socket directory is %s\n" ''${pgLogFile} ''${pgSockDir}

        cleanup() {
            set +e -x
            pg_ctl stop -D ''${pgDir}
            rm -rvf ''${pgDir} ''${pgSockDir} ''${pgLogFile}
            set +x
        }

        trap cleanup EXIT

        set +xe
      fi

      ${oldAttrs.shellHook}
    '';
  };

  dummy = pkgs.stdenv.mkDerivation {
    name = "interactive-uniworx-environment";
    shellHook = "";
  };
in pkgs.stdenv.lib.overrideDerivation dummy override
  #pkgs.stdenv.lib.overrideDerivation drv.env override
