# SPDX-FileCopyrightText: 2023 Luke Granger-Brown <depot@lukegb.com>
#
# SPDX-License-Identifier: Apache-2.0

{ depot, lib, pkgs, ... }@args:

let
  pytumblr2 = ps: ps.buildPythonPackage rec {
    pname = "PyTumblr2";
    version = "0.2.2";

    src = ps.fetchPypi {
      inherit pname version;
      sha256 = "0xpl4v25kaywyr6fbanhsx9rpmbdvb7zs6hcj6m3md3ddkp9whkf";
    };

    propagatedBuildInputs = with ps; [
      future
      requests_oauthlib
    ];

    checkInputs = with ps; [
      nose
      nose-cov
      mock
    ];
  };

  python = pkgs.python3.withPackages (ps: with ps; [
    absl-py
    attrs
    beautifulsoup4
    requests
    requests_oauthlib
    (pytumblr2 ps)
  ]);

  filterSourcePred = (path: type: (type == "regular" &&
      lib.hasSuffix ".py" path ||
      lib.hasSuffix ".html" path
    ) || (
      type == "directory" &&
      baseNameOf path != "__pycache__" &&
      baseNameOf path != "node_modules" &&
      baseNameOf path != "config" &&
      baseNameOf path != "web" &&
      true));

  tumblrcap = pkgs.stdenvNoCC.mkDerivation rec {
    name = "tumblrcap";

    src = builtins.filterSource filterSourcePred ./.;

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

    installPhase = ''
      sitepkgdir="$out/lib/${python.libPrefix}/site-packages"
      pkgdir="$sitepkgdir/tumblrcap"
      mkdir -p $pkgdir
      cp -R \
        *.py \
        $pkgdir

      mkdir "$out/bin"
      makeWrapper "${python}/bin/python" "$out/bin/tumblrcap" \
        --add-flags "-m" \
        --add-flags "tumblrcap" \
        --suffix PYTHONPATH : "$sitepkgdir"
    '';

    passthru.pythonEnv = python;
  };
in
tumblrcap