job "gitea" {
  group "gitea" {
    network {
      mode = "bridge"
      port "http" {
        to = 3000
      }
    }

    service {
      connect {
        sidecar_service {
          proxy {
            upstreams {
              destination_name = "postgres"
              local_bind_port  = 5432
            }
          }
        }
      }
    }

    service {
      name = "code"
      port = "http"

      tags = [
        "traefik.enable=true",
        "traefik.http.routers.gitea.middlewares=auth@file",
      ]

      check {
        type     = "http"
        path     = "/"
        interval = "10s"
        timeout  = "2s"
      }
    }

    task "gitea" {
      driver = "docker"

      config {
        image = "gitea/gitea:latest"

        ports = ["http"]

        volumes = ["local/app.ini:/data/gitea/conf/app.ini"]
      }

      env = {
        USER_UID = "1000"
        USER_GID = "1000"
      }

      resources {
        cpu    = 500
        memory = 512
      }

      volume_mount {
        volume      = "unraid_appdata_gitea"
        destination = "/data"
        read_only   = false
      }

      template {
        data        = <<EOF
# Gitea configuration file
WORK_PATH = /data/

[database]
DB_TYPE = postgres
HOST = localhost:5432
NAME = gitea
USER = gitea
PASSWD = {{ with nomadVar "nomad/jobs/gitea" }}{{ .database_pw }}{{ end }}

[repository]
ROOT = /data/git/repositories

[server]
DOMAIN = code.othrayte.one
SSH_DOMAIN = git.othrayte.one
ROOT_URL = https://code.othrayte.one/

[lfs]
PATH = /data/git/lfs

[log]
MODE = console
LEVEL = info
ROOT_PATH = /data/gitea/log

[security]
INSTALL_LOCK = true
INTERNAL_TOKEN = {{ with nomadVar "nomad/jobs/gitea" }}{{ .internal_token }}{{ end }}
PASSWORD_HASH_ALGO = pbkdf2

[oauth2]
JWT_SECRET = {{ with nomadVar "nomad/jobs/gitea" }}{{ .jwt_secret }}{{ end }}
EOF
        destination = "local/app.ini"
      }
    }

    task "tailscale" {
      driver = "docker"

      config {
        image = "tailscale/tailscale:latest"
      }

      env = {
        TS_HOSTNAME   = "git"
        TS_AUTHKEY    = "${ts_oauthsecret}?ephemeral=true"
        TS_EXTRA_ARGS = "--advertise-tags=tag:nomad"
      }

      resources {
        cpu    = 100
        memory = 64
      }

      lifecycle {
        hook    = "prestart"
        sidecar = true
      }
    }

    volume "unraid_appdata_gitea" {
      type            = "csi"
      read_only       = false
      source          = "unraid_appdata_gitea"
      access_mode     = "single-node-writer"
      attachment_mode = "file-system"

      mount_options {
        mount_flags = ["uid=1000", "gid=1000"]
      }
    }
  }
}
