{ depot, pkgs, ... }:

let
  python = pkgs.python3.withPackages (ps: with ps; [
    django_3
    gunicorn
    psycopg2
    (depot.pkgs.django-allauth.override {
      django = django_3;
    })
    (depot.pkgs.django-tailwind.override {
      django = django_3;
    })
  ]);

  filterSourcePred = (path: type: type != "directory" || (
      baseNameOf path != "__pycache__" &&
      baseNameOf path != "node_modules" &&
      true));
in
pkgs.stdenvNoCC.mkDerivation rec {
  name = "quotes";

  src = builtins.filterSource filterSourcePred ./.;

  buildInputs = with pkgs; [ makeWrapper nodejs ];
  propagatedBuildInputs = [ python ];

  nodeModules = (import ./node-default.nix { inherit pkgs; }).shell.nodeDependencies;

  buildPhase = ''
    cp -R $nodeModules/lib/node_modules theme/static_src/node_modules
  '';
  installPhase = ''
    sitepkgdir="$out/lib/${python.libPrefix}/site-packages"
    pkgdir="$sitepkgdir/quotes"
    mkdir -p $pkgdir
    cp -R \
      quotesapp \
      quotedb \
      templates \
      static \
      discordguild \
      theme \
      $pkgdir

    mkdir "$out/bin"
    makeWrapper "${python}/bin/gunicorn" "$out/bin/quotes" \
      --add-flags "quotes.quotesapp.wsgi" \
      --suffix PYTHONPATH : "$sitepkgdir"
    makeWrapper "${python}/bin/django-admin" "$out/bin/quotes-manage" \
      --set DJANGO_SETTINGS_MODULE "quotes.quotesapp.prod_settings" \
      --suffix PYTHONPATH : "$sitepkgdir"

    mkdir -p "$out/share/static"
    export STATIC_ROOT="$out/share/static"
    export DJANGO_SETTINGS_MODULE=quotes.quotesapp.settings
    export PYTHONPATH=$PYTHONPATH''${PYTHONPATH:+':'}"$sitepkgdir"
    mkdir $NIX_BUILD_TOP/tmp
    export HOME=$NIX_BUILD_TOP/tmp
    django-admin tailwind build
    django-admin collectstatic --no-input

    chmod -R +w $pkgdir/theme/static $pkgdir/theme/static_src
    rm -rf $pkgdir/theme/static $pkgdir/theme/static_src
  '';

  passthru.pythonEnv = python;
}