/*
nix-build .
./result/bin/hazel-editor
*/

{ pkgs ? import <nixpkgs> {} }:

let
  rev = "614e28d2baa6a948ad36a355c8b190c246631918";
  sha256 = "AhZfpZ+40406uupNhZwNVNcRb6Aep/4mhpvL55aG+rM=";
  version = "2022-02-28";
  #commitTime = "02/28/22 19:03"; # git log -1 --format=%at | xargs -I{} date -d @{} +%m/%d/%y\ %H:%M
  # getting the commit time from github API is not possible, cos timezone is missing
in

with pkgs;

pkgs.stdenv.mkDerivation {

  pname = "hazel";
  inherit version;

  src = pkgs.fetchFromGitHub {
    owner = "hazelgrove";
    repo = pname;
    inherit rev sha256;
  };

  # note: cant use shellHook, otherwise CAML_LD_LIBRARY_PATH is not set

  buildInputs = with pkgs; [
    gnumake
    ocaml
    opam
    dune_2
  ] ++ (with pkgs.ocamlPackages; [
    findlib
    base
    reason
    ppx_let
    ppx_sexp_conv
    ppx_expect
    sexplib
    incr_dom
    camomile
    time_now
    js_of_ocaml
    js_of_ocaml-ppx
    js_of_ocaml-compiler
  ]);

  #  echo let commit_time = \"${commitTime}\"\;
  patchPhase = ''
    cat >'src/hazelweb/Version_autogenerator.sh' <<EOF
    echo "/* Auto-generated by Version_autogenerator.sh during build */"
    echo let branch = \"dev\"\;
    echo let commit_hash_short = \"${builtins.substring 0 7 rev}\"\;
    echo let commit_time = \"${version}\"\;
    EOF
  '';

  buildPhase = "make dev";

  # ${pkgs.xdg-utils}/bin/xdg-open $out/opt/hazel-editor/_build/default/src/hazelweb/www/index.html
  # too simple. we want to:
  # open a html file in default browser, not text editor,
  # when text editor is set as default app for html files
  # https://stackoverflow.com/a/69986901/10440128

  installPhase = ''
    mkdir -p $out/opt
    cp -r . $out/opt/hazel-editor

    mkdir -p $out/bin

    cat >$out/bin/hazel-editor <<EOF
    #! ${pkgs.runtimeShell}
    url=file://$out/opt/hazel-editor/_build/default/src/hazelweb/www/index.html
    protocol=http
    app=\$(${pkgs.xdg-utils}/bin/xdg-mime query default x-scheme-handler/\$protocol)
    [ -z "\$app" ] && {
      echo "error: xdg-mime could not find default app for protocol \$protocol"
      exit 1
    }
    app=\$(basename \$app .desktop)
    ${pkgs.gnome.gtk}/bin/gtk-launch \$app "\$url"
    EOF

    chmod +x $out/bin/hazel-editor
  '';

  meta = with lib; {
    description = "a live functional programming environment with typed holes. web-based structural editor";
    homepage = "https://github.com/hazelgrove/hazel";
    license = licenses.mit;
    platforms = platforms.all;
  };
}
