{ config, lib, pkgs, ... }:

with lib;

let

  library = import <library> { inherit pkgs lib; };

  sync-repo = library.jenkins.syncJob;
  job = library.jenkins.job;

in {

  environment.systemPackages = [ pkgs.cabal-install ];

  services.nginx = {
    enable = true;
    virtualHosts = {
      "jenkins.${config.networking.hostName}.private" = {
        locations."/" = {
          proxyPass =
            "http://localhost:${toString config.services.jenkins.port}";
          extraConfig = ''
            proxy_set_header        Host $host:$server_port;
            proxy_set_header        X-Real-IP $remote_addr;
            proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header        X-Forwarded-Proto $scheme;

            proxy_read_timeout  90;
            proxy_redirect      http://localhost:${
              toString config.services.jenkins.port
            } https://jenkins.${config.networking.hostName}.private/;
          '';
        };
      };
    };
  };

  krops.userKeys."accessToken" = {
    user = "jenkins";
    source = toString <secrets/jenkins/accessToken>;
    requiredBy = [ "jenkins-job-builder.service" ];
  };

  services.jenkins = {
    enable = true;
    home = "/home/jenkins";
    port = 10420;

    # Plugins to Install:
    # - all the plugins recommended at the setup
    # - Build pipeline
    # - SSH Agent
    # - mattermost plugin
    jobBuilder = {
      enable = true;

      # create an access token in the admin users panel
      accessTokenFile = config.krops.userKeys."accessToken".target;
      accessUser = "admin";

      # https://docs.openstack.org/infra/jenkins-job-builder/definition.html#modules
      nixJobs = let
        # ssh username + key
        gogs-id = "bc584c99-0fb7-43fb-af75-4076d64c51b2";
        # ssh username + key
        github-id = "bc584c99-0fb7-43fb-af75-4076d64c51b2";
        # ssh username + key
        sshSputnik = "d91eb57c-5bff-434c-b317-68aad46848d7";

        sync-to-github = name: source: target:
          sync-repo name {
            url = source;
            credentialsId = gogs-id;
          } {
            url = target;
            credentialsId = github-id;
          };

      in [

        (job "deploy-gaykraft" {
          url = "ssh://gogs@workhorse.private:2222/palo/gaykraft.git";
          credentialsId = gogs-id;
        } [
          { "build" = [ "nix-shell --run build" ]; }
          {
            "publish" = [{
              script = "nix-shell --run publish";
              credentialsId = sshSputnik;
            }];
          }
        ])

        (job "sync-retiolum" {
          url = "git@github.com:krebs/retiolum.git";
          credentialsId = github-id;
          triggers = [{ timed = "H/30 * * * *"; }];
        } [
          {
            "Download Files" = [
              "chmod 755 hosts"
              "chmod 755 -R hosts"
              ''
                nix-shell -p curl -p gnutar -p bzip2 --run "curl https://lassul.us/retiolum-hosts.tar.bz2 | tar xvjf - || true"''
              "chmod 755 -R etc.hosts"
              ''
                nix-shell -p curl --run "curl https://lassul.us/retiolum.hosts > etc.hosts || true"''
            ];
          }
          {
            "update repo" = [
              ''nix-shell -p git --run "git add ."''
              ''
                nix-shell -p git --run "git -c user.name=\'Ingolf Wagner\' -c user.email=\'contact@ingolf-wagner.de\' commit -m update-`date +%Y-%m-%dT%H:%M:%S` || exit 0"''
            ];
          }
          {
            Push = [{
              script = ''nix-shell -p git --run "git push origin master"'';
              credentialsId = github-id;
            }];
          }
        ])

        (job "test-terranix" {
          url = "ssh://gogs@workhorse.private:2222/terranix/terranix.git";
          credentialsId = github-id;
          branch = "develop";
        } [{
          "run Tests" = [ ''nix-shell tests/shell.nix --run "test-terranix"'' ];
        }])

        (job "test-taskninja" {
          url = "ssh://gogs@workhorse.private:2222/palo/taskninja.git";
          credentialsId = gogs-id;
        } [
          {
            "Create Shell" = [
              ''
                nix-shell -p cabal2nix --run "cabal2nix --shell file://. > jenkins.nix"''
            ];
          }
          { Update = [ ''nix-shell ./jenkins.nix --run "cabal update"'' ]; }
          {
            Configure = [
              ''nix-shell ./jenkins.nix --run "cabal configure --enable-tests"''
              ''
                nix-shell ./jenkins.nix --run "cabal install --only-dependencies"''
            ];
          }
          { Build = [ ''nix-shell ./jenkins.nix --run "cabal build"'' ]; }
          { Test = [ ''nix-shell ./jenkins.nix --run "cabal test"'' ]; }
        ])

        # sync to github
        # --------------
        (sync-to-github "sync-radiodj"
          "ssh://gogs@workhorse.private:2222/crashburn_radio/radio-dj2.git"
          "git@github.com:crashburn-radio/radio-dj.git")
        (sync-to-github "sync-radiodj-tracks"
          "ssh://gogs@workhorse.private:2222/crashburn_radio/radio-dj-tracks.git"
          "git@github.com:crashburn-radio/radio-dj-tracks.git")

        (sync-to-github "sync-krops-module"
          "ssh://gogs@workhorse.private:2222/nix-modules/krops.git"
          "git@github.com:mrVanDalo/module.krops.git")

        (sync-to-github "sync-cluster-module"
          "ssh://gogs@workhorse.private:2222/nix-modules/cluster.git"
          "git@github.com:mrVanDalo/module.cluster.git")

        (sync-to-github "sync-backup-module"
          "ssh://gogs@workhorse.private:2222/nix-modules/backup.git"
          "git@github.com:mrVanDalo/module.backup.git")

        (sync-to-github "sync-module-tinc"
          "ssh://gogs@workhorse.private:2222/palo/nixos-tinc.git"
          "git@github.com:mrVanDalo/nixos-tinc.git")

        (sync-to-github "sync-memo"
          "ssh://gogs@workhorse.private:2222/palo/memo.git"
          "git@github.com:mrVanDalo/memo.git")

        (sync-to-github "sync-diagrams-template"
          "ssh://gogs@workhorse.private:2222/palo/diagrams-template.git"
          "git@github.com:mrVanDalo/diagrams.git")

        (sync-to-github "sync-terranix"
          "ssh://gogs@workhorse.private:2222/terranix/terranix.git"
          "git@github.com:mrVanDalo/terranix.git")

        (sync-to-github "sync-terranix.org"
          "ssh://gogs@workhorse.private:2222/terranix/terranix.org.git"
          "git@github.com:mrVanDalo/terranix-website.git")

        (sync-to-github "sync-terranix-hcloud"
          "ssh://gogs@workhorse.private:2222/terranix/hcloud.git"
          "git@github.com:mrVanDalo/terranix-hcloud.git")

        (sync-to-github "sync-plops"
          "ssh://gogs@workhorse.private:2222/palo/plops.git"
          "git@github.com:mrVanDalo/plops.git")

        (sync-to-github "sync-image-generator"
          "ssh://gogs@workhorse.private:2222/palo/image-generator2.git"
          "git@github.com:mrVanDalo/image-generator.git")

        (sync-to-github "sync-image-generator-lib"
          "ssh://gogs@workhorse.private:2222/palo/image-generator-lib.git"
          "git@github.com:mrVanDalo/image-generator-examples.git")

        (sync-to-github "sync-tech.ingolf-wagner.de"
          "ssh://gogs@workhorse.private:2222/palo/tech.ingolf-wagner.de.git"
          "git@github.com:mrVanDalo/tech.ingolf-wagner.de.git")

        (sync-to-github "sync-LineageOS-build"
          "ssh://gogs@git.ingolf-wagner.de:443/palo/LineagoOS-build.git"
          "git@github.com:mrVanDalo/LineagoOS-build.git")

        (sync-to-github "sync-http-errors"
          "ssh://gogs@git.ingolf-wagner.de:443/palo/http-errors.git"
          "git@github.com:mrVanDalo/http-errors.git")
        (sync-to-github "sync-light-control"
          "ssh://gogs@git.ingolf-wagner.de:443/palo/light-control.git"
          "git@github.com:mrVanDalo/light-control.git")

      ];
    };
  };

}