variable "wait_on" {
  type        = any
  description = "Resources to wait on"
  default     = true
}

variable "server_ip" {
  type = string
}

variable "ssh_private_key_path" {
  type = string
}

variable "server_domain" {
  type = string
}

variable "postgres_password" {
  type = string
  sensitive = true
}

resource "random_password" "forgejo_secret_key" {
  length  = 64
  special = false
}

resource "random_password" "forgejo_internal_token" {
  length  = 64
  special = false
}

resource "random_password" "forgejo_jwt_secret" {
  length  = 32
  special = false
}

module "psql_db" {
  source = "../postgres/tenant"
  
  tenant_name    = "forgejo"
  admin_username = "postgres"
  admin_password = var.postgres_password
  server_ip      = var.server_ip
  ssh_private_key_path = var.ssh_private_key_path
}

module "forgejo" {
  source = "../quadlet-app"
  wait_on = var.wait_on

  server_ip            = var.server_ip
  ssh_private_key_path = var.ssh_private_key_path

  app_name = "forgejo"
  image    = "codeberg.org/forgejo/forgejo:13.0"
  ports    = ["3000:3000", "2222:22"]
  volumes  = [
    "/opt/storage/data/forgejo:/data:Z",
    "/etc/localtime:/etc/localtime:ro"
  ]
  
  environment = {
    USER_UID = "1000"
    USER_GID = "1000"
    FORGEJO__database__DB_TYPE = "postgres"
    FORGEJO__database__HOST = "systemd-postgres:5432"
    FORGEJO__database__NAME = "forgejo"
    FORGEJO__database__USER = module.psql_db.username
    FORGEJO__database__PASSWD = module.psql_db.password
    FORGEJO__server__DOMAIN = "forgejo.${var.server_domain}"
    FORGEJO__server__ROOT_URL = "https://forgejo.${var.server_domain}/"
    FORGEJO__server__SSH_DOMAIN = "forgejo.${var.server_domain}"
    FORGEJO__server__SSH_PORT = "2222"
    FORGEJO__security__INSTALL_LOCK = "true"
    FORGEJO__security__SECRET_KEY = random_password.forgejo_secret_key.result
    FORGEJO__security__INTERNAL_TOKEN = random_password.forgejo_internal_token.result
    FORGEJO__oauth2__JWT_SECRET = random_password.forgejo_jwt_secret.result
  }
  
  healthcmd = "curl -f http://localhost:3000/api/v1/version || exit 1"

  haproxy_services = [
    {
      name   = "forgejo"
      domain = "forgejo.${var.server_domain}"
      port   = "3000"
      host   = "127.0.0.1"
      tls    = false
    }
  ]
}

output "app_urls" {
  value = module.forgejo.app_urls
}

output "installed" {
  value = true
  depends_on = [module.forgejo.installed]
}

output "secret_key" {
  value = random_password.forgejo_secret_key.result
  sensitive = true
}

output "internal_token" {
  value = random_password.forgejo_internal_token.result
  sensitive = true
}

output "jwt_secret" {
  value = random_password.forgejo_jwt_secret.result
  sensitive = true
}
