# =============================================================================
# DB Schema Initialisation — runs serverless.sql inside the ACK cluster
# using the remote_python module (same pattern as aws_modules/rds-db).
# =============================================================================

data "external" "github_settings" {
  program = ["bash", "-c", <<-EOT
    cat <<EOF
    {
        "gh_token": "$GH_TOKEN",
        "gh_rev": "$(git rev-parse HEAD)"
    }
    EOF
  EOT
  ]

  lifecycle {
    postcondition {
      condition     = self.result.gh_token != ""
      error_message = "env GH_TOKEN not set"
    }
  }
}

module "init_db" {
  source          = "../../modules/remote_python"
  kubeconfig_path = module.kubeconfig.path

  script_url = join("", [
    "https://",
    data.external.github_settings.result.gh_token,
    "@raw.githubusercontent.com/tidbcloud/auto-deploy/",
    chomp(data.external.github_settings.result.gh_rev),
    "/scripts/init-alicloud-rds-database.py",
  ])

  script_parameters = [
    "--host", local.rds_connection_string,
    "--port", local.rds_port,
    "--user", alicloud_rds_account.this.account_name,
    "--password", random_password.rds.result,
    "--db-name", alicloud_db_database.kubestore.data_base_name,
    "--sql-b64", base64encode(file("${path.module}/serverless.sql")),
  ]

  depends_on = [
    alicloud_db_account_privilege.kubestore,
    null_resource.alicloud_db_whitelist_template_attachment,
  ]
}
