terraform {
  required_providers {
    random = {
      source  = "hashicorp/random"
      version = "~> 3.6"
    }
    postgresql = {
      source  = "cyrilgdn/postgresql"
      version = "~> 1.22"
    }
  }
}

# Generate random password for the tenant user
resource "random_password" "tenant_password" {
  length           = 32
  special          = false
  min_upper        = 2
  min_lower        = 2
  min_numeric      = 2
}

# Create SSH tunnel to PostgreSQL on VPS
module "db_tunnel" {
  source       = "flaupretre/tunnel/ssh"
  version      = "2.3.0"

  target_host = "127.0.0.1"
  target_port = var.target_port

  gateway_host = var.server_ip
  gateway_user = var.ssh_user
  gateway_port = 22
}

provider postgresql {
  alias    = "tunnel"
  host     = module.db_tunnel.host
  port     = module.db_tunnel.port
  username = var.admin_username
  password = var.admin_password
  database = "postgres"
  sslmode = "disable"
  superuser = false
}


#---- Database

resource postgresql_database db {
  provider = postgresql.tunnel

  name       = var.tenant_name
  owner      = var.tenant_name

  encoding   = "UTF8"
  lc_collate = "C"
  lc_ctype   = "C"
}

#---- DB user/role

resource postgresql_role role {
  provider = postgresql.tunnel

  name     = var.tenant_name
  login    = true
  password = random_password.tenant_password.result
}

#---- Grant
# SQL: grant all on <db>.* to <user>@'%';

resource postgresql_grant grant {
  provider    = postgresql.tunnel

  object_type = "database"
  database    = var.tenant_name
  role        = var.tenant_name
  privileges  = ["ALL"]
}