from app.terraform.list import ListAutomation


class ListGithubAutomation(ListAutomation):
    short_name = "list_github"
    description = "Update mirror lists in GitHub repositories"
    provider = "github"
    always_refresh = True

    # Where there is more than 1 file in the same repository, there's a race condition
    # TODO: file an issue in the github about this, GitLab had a similar issue but fixed it
    parallelism = 1

    template_parameters = [
        "github_api_key"
    ]

    template = """
    terraform {
      {{ backend_config }}
      required_providers {
        github = {
          source = "integrations/github"
          version = "~> 4.20.1"
        }
      }
    }

    {% for list in lists %}
    provider "github" {
      alias               = "list_{{ list.id }}"
      owner               = "{{ list.container.split("/")[0] }}"
      token               = "{{ github_api_key }}"
    }

    data "github_repository" "repository_{{ list.id }}" {
      provider            = github.list_{{ list.id }}
      name                = "{{ list.container.split("/")[1] }}"
    }

    resource "github_repository_file" "file_{{ list.id }}" {
      provider            = github.list_{{ list.id }}
      repository          = data.github_repository.repository_{{ list.id }}.name
      branch              = "{{ list.branch }}"
      file                = "{{ list.filename }}"
      content             = file("{{ list.format }}.{{ list.pool.pool_name }}.{{ list.encoding }}")
      commit_message      = "Managed by Terraform"
      commit_author       = "Terraform User"
      commit_email        = "terraform@api.otf.is"
      overwrite_on_create = true
    }
    {% endfor %}
    """
