{ lib
, stdenvNoCC
, ffmpeg
, rtmpdump
, atomicparsley
, callPackage
, fetchFromGitHub
, fetchPypi
, fetchpatch
, makeWrapper
, python3Packages }: with python3Packages; let
  mkPypi = pname: version: src: format: buildPythonPackage {
    inherit pname version src format;
    doCheck = false;
    nativeBuildInputs = [ setuptools ];
  };

  mkPypi' = pname: version: hash: format: mkPypi pname version
  (fetchPypi {
    inherit pname version hash;
  }) format;

  mkPypi'' = pname: version: hash: mkPypi' pname version hash
  "setuptools";

  django-compat = mkPypi'' "django-compat" "1.0.15" "sha256-OsmjvtxWuTZdnrJBvFFX0MGTdpv5lfmnjcG8JOfCMxs=";
  django-appconf = mkPypi'' "django-appconf" "1.0.6" "sha256-z+h+qCfE7gS5pw+rkLhtcEywLymB+J2oQjyw+r+I778=";
  django-basicauth = mkPypi'' "django-basicauth" "0.5.3" "sha256-FenjZvaY9TxxseeU2v6gYPmQoqxVa65rczDdJTJKCRw=";
  django-sass-processor = mkPypi'' "django-sass-processor" "1.4" "sha256-sX850H06dRCuxCXBkZN+IwUC3ut8pr9pUKGt+LS3wcM=";
  django-background-tasks = mkPypi'' "django-background-tasks" "1.2.5" "sha256-4bGejUlaJ2ydZMWh/4tBEy910vWORb5xt4ZQ2tWa+d4=";

  django-compressor = let
    pname = "django-compressor";
    version = "4.4";
  in mkPypi pname version (fetchFromGitHub {
    owner = pname;
    repo = pname;
    rev = "refs/tags/${version}";
    hash = "sha256-c9uS5Z077b23Aj8jV30XNsshbEfrLRX3ozXasitQ6UQ=";
  }) "setuptools";

  app = buildPythonApplication rec {
    pname = "tubesync";
    version = "0.13.6";
    format = "other";

    src = fetchFromGitHub {
      name = "${pname}-src";
      owner = "meeb";
      repo = pname;
      rev = "v${version}";
      hash = "sha256-5l1HkMoTn99rNeeK5u+KoFejTFi2LfLyt8upq7xwrj0=";
    };

    patches = [
      ./gunicorn-env.patch
      ./state-dir-env.patch
      ./database-local-socket.patch
      ./ensure-fragments.patch
    ];

    propagatedBuildInputs = [
      yt-dlp requests
      httptools pillow
      gunicorn whitenoise
      psycopg2 mysqlclient
      redis hiredis
      libsass six
    ] ++ [
      django_3
      django-compat
      django-appconf
      django-compressor
      django-basicauth
      django-sass-processor
      django-background-tasks
    ];

    buildPhase = ''
      mv "tubesync/tubesync/local_settings.py.container" "tubesync/tubesync/local_settings.py"
      rm "tubesync/tubesync/local_settings.py.example"
      rm "tubesync/tubesync/local_settings.py.container.orig"

      python3 tubesync/manage.py compilescss
      python3 tubesync/manage.py collectstatic --no-input
    '';

    installPhase = ''
      mkdir -p "$out"
      cp -r "tubesync" "$out/app"

      FFMPEG_VERSION=$(${ffmpegFix}/bin/ffmpeg -version | head -n 1 | awk '{ print $3 }')
      echo "ffmpeg_version = '$FFMPEG_VERSION'" >> "$out/app/common/third_party_versions.py"

      mv "$out/app/static" "$out/static"
      ln -s "/tmp/tubesync/static" "$out/app/static"
    '';
  };

  ffmpegFix = ffmpeg.overrideAttrs (finalAttrs: previousAttrs: {
    patches = previousAttrs.patches ++ [ (fetchpatch {
      name = "avformat-webvttdec-skip-style-region.patch";
      url = "https://git.ffmpeg.org/gitweb/ffmpeg.git/patch/51d303e20cbb0874172f50b5172c515a973587d4";
      hash = "sha256-dxCjKZUz2H2QyktsprkzyfNp5aDG6X8deF4ZGdvhvfk=";
    }) ];
  });
in stdenvNoCC.mkDerivation {
  pname = "${app.pname}-wrapped";
  inherit (app) version;

  nativeBuildInputs = [ makeWrapper ];
  unpackPhase = "true";
  installPhase = let
    prefix = ''--prefix PATH : "${lib.makeBinPath [
      ffmpegFix rtmpdump atomicparsley
    ]}"'';
  in ''
    mkdir -p "$out/bin"

    makeWrapper "${python}/bin/python3" "$out/bin/tubesync-worker" \
    --chdir ${app}/app --add-flags \
    "${app}/app/manage.py process_tasks" \
    ${prefix}

    makeWrapper "${gunicorn}/bin/gunicorn" "$out/bin/tubesync-gunicorn" \
    --chdir ${app}/app --add-flags \
    "-c ${app}/app/tubesync/gunicorn.py --capture-output tubesync.wsgi:application" \
    ${prefix}

    makeWrapper "${python}/bin/python3" "$out/bin/tubesync-migrate" \
    --chdir "${app}/app" --add-flags \
    "${app}/app/manage.py migrate"
  '';

  passthru = {
    inherit app;
    pythonPath = makePythonPath app.propagatedBuildInputs;
  };
}
