{ config, pkgs, ... }:
let
  flarumPackage = with pkgs; stdenv.mkDerivation {
    name = "flarum-package";
    src = fetchFromGitHub {
      owner = "flarum";
      repo = "flarum";
      rev = "v0.1.0-beta.13";
      sha256 = "0mj6w7nibdqmi7lx2r5d9yiif6lb584l93551i115a9ly3s4yinn";
    };
    buildPhase =
      ''
      cp ${./flarum}/* .
      '';
    installPhase =
      ''
      cp -ar . $out
      '';
  };
  flarum = import "${flarumPackage}" {
    inherit pkgs;
    noDev = true;
  };
  cfg = config.services.flarum;
in
{
  options.services.flarum = with pkgs.lib; {
    user = mkOption {
      type = types.str;
      default = "nobody";
    };
    group = mkOption {
      type = types.str;
      default = "nogroup";
    };
    installPath = mkOption {
      type = types.str;
      default = "/var/www/flarum";
    };
  };

  config.systemd.services.flarum-install = {
    description = "Flarum installation";
    before = [ "nginx.service" "phpfm-flarum.service" ];
    wantedBy = [ "multi-user.target" ];
    serviceConfig = {
      Type = "oneshot";
    };
    path = [ pkgs.rsync ];
    script = with cfg; ''
      mkdir -p ${installPath}
      rsync --links --recursive ${flarum}/ ${installPath}
      for d in ${installPath} ${installPath}/public/assets \
          ${installPath}/storage ${installPath}/storage/*
      do
          chown ${user}:${group} $d
          chmod 0775 $d
      done
    '';
  };
}