WORKSPACE: use nix for python/go if available

This introduces Nix, the package manager, and nixpkgs, the package
collection, into hscloud's bazel build machinery.

There are two reasons behind this:

 - on NixOS, it's painful or at least very difficult to run hscloud out
   of the box. Especially with rules_go, that download a blob from the
   Internet to get a Go toolchain, it just fails outright. This solves
   this and allows hscloud to be used on NixOS.

 - on non-NixOS platforms that still might have access to Nix this
   allows to somewhat hermeticize the build. Notably, Python now comes
   from nixpkgs, and is fabricobbled in a way that makes pip3_import
   use Nix system dependencies for ncurses and libpq.

This has been tested to run ci_presubmit on NixOS 20.09pre and Gentoo
~amd64.

Change-Id: Ic16e4827cb52a05aea0df0eed84d80c5e9ae0e07
diff --git a/third_party/nix/python.nix b/third_party/nix/python.nix
new file mode 100644
index 0000000..5571a60
--- /dev/null
+++ b/third_party/nix/python.nix
@@ -0,0 +1,46 @@
+# This is a Python interpreter wrapper that's passed to pip3_import under
+# NixOS.
+# It allows us to build some pip wheels under NixOS that require special
+# system libraries. This is quite hacky, it would be much better if we could
+# somehow tell pip3_import that a given package needs to be built within a
+# given environment.
+
+with import <nixpkgs> {};
+
+let
+  # Add cffi for import _cffi_backend in `cryptography` to work.
+  py = pkgs.python37.withPackages (ps: with ps; [ cffi ]);
+
+# We use mkDerivation instead of writeScript or writeScriptBin as we need a
+# derivation that both:
+# - has a directory structure (for rules_nixpkgs to be able to use it)
+# - has the Python interpreter directly in that structure and not in bin/, as
+#   rules_python's pip3_import interpreter_path requires a file target, and
+#   will not take an alias. Meanwhile, rules_nixpkgs only creates a BUILD file
+#   in the root path of the external repository (which is populated with a
+#   symlink tree from the nix derivation), so we can onlly directly reference
+#   file in the root of a Nix derivation.
+in stdenv.mkDerivation {
+  name = "py-wrapper";
+  version = "1.0";
+  src = ./.;
+  unpackPhase = "";
+  buildPhase = ''
+    mkdir -p $out
+    cat > $out/python3 <<EOF
+#!/bin/bash
+
+# pyscopg wants libpq, and uses pg_config to find paths. Inject pg_config into
+# the Python interpreter's path.
+export PATH="${pkgs.postgresql}/bin:\$PATH"
+
+# uWSGI has a truly cheese-grade build system, and this is the only way to let
+# it know where to find ncurses.
+export LDFLAGS="-L${pkgs.ncurses}/lib"
+exec ${py}/bin/python3 "\$@"
+EOF
+  '';
+  installPhase = ''
+    chmod +x $out/python3
+  '';
+}