{ nixpkgs ? import <nixpkgs> {}, compiler ? null }:

let
  inherit (nixpkgs) pkgs;

  haskellPackages = if isNull compiler
                       then pkgs.haskellPackages
                       else pkgs.haskell.packages."${compiler}";

  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; [ postgresql ]) ++ (with haskellPackages; [ stack yesod-bin hlint cabal-install ]);
    shellHook = ''
      export PROMPT_INFO="${oldAttrs.name}"

      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() {
          pg_ctl stop -D ''${pgDir}
          rm -rvf ''${pgDir} ''${pgSockDir} ''${pgLogFile}
      }

      trap cleanup EXIT

      ${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
