{ config, containerCfg, pkgs, lib, builder, name,... }:
let 
  version = "v2";
  serverCfg = config.syscfg.server;

in {
  requires = {
    secrets = [ name ];
    databases = [ name ];
  };

  runtime = {
    paths = [{
      path = "${serverCfg.path.config.path}/immich";
      dirs = ["cache" "thumbs" "encoded-video"];
      mode = "0755";
    }{
      path = "${serverCfg.path.data.path}/immich/";
      dirs = ["backups"];
      mode = "0755";
    }];

    containers = {
      server = builder.mkContainer {
        subdomain = containerCfg.subdomain;
        image = "ghcr.io/immich-app/immich-server:${version}";
        port = 2283;
        secret = name;
        extraEnv = {
          DB_HOSTNAME = builder.host;
          REDIS_HOSTNAME = builder.host;
          DB_USERNAME = "immich_user";
          DB_DATABASE_NAME = "immich_db";
          IMMICH_TRUSTED_PROXIES = "10.0.0.0/8";
          IMMICH_MACHINE_LEARNING_URL = "http://immich-ml:3003";
          # IMMICH_ALLOW_SETUP = "false";
          IMMICH_IGNORE_MOUNT_CHECK_ERRORS = "true";
        };
        overrides = {
          volumes = [
            "${serverCfg.path.photo.path}:/data/upload"
            "${serverCfg.path.data.path}/immich/backups:/data/backups"
            "${serverCfg.path.config.path}/immich/thumbs:/data/thumbs"
            "${serverCfg.path.config.path}/immich/encoded-video:/data/encoded-video"
          ];
        };
      };

      ml = builder.mkContainer {
        image = "ghcr.io/immich-app/immich-machine-learning:${version}";
        port = 3003;
        overrides = {
          volumes = [
            "${serverCfg.path.config.path}/immich/cache:/cache"
          ];
        };
      };
    };

    setup = {
      trigger = "server";
      envFile = config.sops.secrets."CUSTOM".path;
      script = pkgs.writeShellScript "setup" ''
          PSQL="${pkgs.postgresql}/bin/psql -U postgres"
          $PSQL -d "immich_db" -tAc "CREATE EXTENSION IF NOT EXISTS vchord CASCADE;"
          $PSQL -d "immich_db" -tAc "CREATE EXTENSION IF NOT EXISTS earthdistance CASCADE;"
          $PSQL -d "immich_db" -tAc "ALTER EXTENSION vchord UPDATE;"
          $PSQL -d "immich_db" -tAc "ALTER EXTENSION earthdistance UPDATE;"

          IMMICH_URL="https://${containerCfg.subdomain}.${serverCfg.domain}"
          until [[ "$(${pkgs.curl}/bin/curl -s -o /dev/null -w "%{http_code}" "$IMMICH_URL")" =~ (200|301|302) ]]; do
            sleep 5
          done
          ${pkgs.curl}/bin/curl -X POST "$IMMICH_URL/api/auth/admin-sign-up" \
            -H "Content-Type: application/json" -H "Accept: application/json" \
            -d '{ "email": "'"$DEFAULT_ADMIN_EMAIL"'", "password": "'"$DEFAULT_ADMIN_PASSWORD"'", "name": "'"$DEFAULT_ADMIN_USERNAME"'" }'

          IMMICH_TOKEN=$(${pkgs.curl}/bin/curl -sSf -X POST "$IMMICH_URL/api/auth/login" \
          -H "Content-Type: application/json" \
          -d '{ "email": "'"$DEFAULT_ADMIN_EMAIL"'", "password": "'"$DEFAULT_ADMIN_PASSWORD"'"}' \
          | ${pkgs.jq}/bin/jq -r '.accessToken')        

          ${lib.optionalString (serverCfg.containers ? authentik) ''
          ${pkgs.curl}/bin/curl -s -X GET "$IMMICH_URL/api/system-config" -H "Cookie: immich_access_token=$IMMICH_TOKEN; immich_auth_type=password; immich_is_authenticated=true" | \
          ${pkgs.jq}/bin/jq '.oauth.enabled = true | 
                            .oauth.autoRegister = true |
                            .oauth.autoLaunch = true |
                            .oauth.signingAlgorithm = "RS256" |
                            .oauth.profileSigningAlgorithm = "RS256" |
                            .oauth.clientId = "immich" | 
                            .oauth.clientSecret = "'"$IMMICH_OAUTH_SECRET"'" | 
                            .oauth.issuerUrl = "https://${serverCfg.containers.authentik.subdomain}.${serverCfg.domain}/application/o/immich/" | 
                            .oauth.scope = "openid profile email" |
                            .oauth.buttonText = "Login with SSO"' | \
          ${pkgs.curl}/bin/curl -s -X PUT "$IMMICH_URL/api/system-config" -H "Cookie: immich_access_token=$IMMICH_TOKEN; immich_auth_type=password; immich_is_authenticated=true" -H "Content-Type: application/json" -d @-
          ''}

          ${pkgs.curl}/bin/curl -s -X GET "$IMMICH_URL/api/system-config" -H "Cookie: immich_access_token=$IMMICH_TOKEN; immich_auth_type=password; immich_is_authenticated=true" | \
          ${pkgs.jq}/bin/jq '.storageTemplate.enable = true |
                            .storageTemplate.template = "{{y}}/{{#if album}}{{album}}{{else}}{{MM}}{{/if}}/{{filename}}"' | \
          ${pkgs.curl}/bin/curl -s -X PUT "$IMMICH_URL/api/system-config" -H "Cookie: immich_access_token=$IMMICH_TOKEN; immich_auth_type=password; immich_is_authenticated=true" -H "Content-Type: application/json" -d @-
          
      '';
    };
  };
}
