from app.models.cloud import CloudProvider
from app.terraform.bridge import BridgeAutomation


class BridgeGandiAutomation(BridgeAutomation):
    short_name = "bridge_gandi"
    description = "Deploy Tor bridges on GandiCloud VPS"
    provider = CloudProvider.GANDI

    template_parameters = [
        "ssh_public_key_path",
        "ssh_private_key_path"
    ]

    template = """
    terraform {
      {{ backend_config }}
      required_providers {
        openstack = {
          source  = "terraform-provider-openstack/openstack"
          version = "~> 1.42.0"
        }
      }
    }

    locals {
      public_ssh_key = "{{ ssh_public_key_path }}"
      private_ssh_key = "{{ ssh_private_key_path }}"
    }

    {% for resource in destroyed_resources %}
    {% set bridge, bridgeconf, account = resource %}
    provider "openstack" {
      auth_url = "https://keystone.sd6.api.gandi.net:5000/v3"
      user_domain_name = "public"
      project_domain_name = "public"
      user_name = "{{ account.credentials["gandi_openstack_user"] }}"
      password = "{{ account.credentials["gandi_openstack_password"] }}"
      tenant_name = "{{ account.credentials["gandi_openstack_tenant_id"] }}"
      region = "FR-SD6"
      alias = "account_{{ bridge.id }}"
    }
    {% endfor %}

    {% for resource in active_resources %}
    {% set bridge, bridgeconf, account = resource %}
    provider "openstack" {
      auth_url = "https://keystone.sd6.api.gandi.net:5000/v3"
      user_domain_name = "public"
      project_domain_name = "public"
      user_name = "{{ account.credentials["gandi_openstack_user"] }}"
      password = "{{ account.credentials["gandi_openstack_password"] }}"
      tenant_name = "{{ account.credentials["gandi_openstack_tenant_id"] }}"
      region = "FR-SD6"
      alias = "account_{{ bridge.id }}"
    }

    module "bridge_{{ bridge.id }}" {
      providers = {
        openstack = openstack.account_{{ bridge.id }}
      }
      source = "{{ terraform_modules_path }}/terraform-openstack-tor-bridge"
      namespace = "{{ global_namespace }}"
      name = "bridge"
      attributes = ["{{ bridge.id }}"]
      ssh_public_key = local.public_ssh_key
      ssh_private_key = local.private_ssh_key
      contact_info = "did not write the code to populate yet"
      distribution_method = "{{ bridgeconf.method }}"

      image_name = "Debian 11 Bullseye"
      flavor_name = "V-R1"
      external_network_name = "public"
      require_block_device_creation = true
    }

    output "bridge_hashed_fingerprint_{{ bridge.id }}" {
      value = module.bridge_{{ bridge.id }}.hashed_fingerprint
    }

    output "bridge_bridgeline_{{ bridge.id }}" {
      value = module.bridge_{{ bridge.id }}.bridgeline
      sensitive = true
    }
    {% endfor %}
    """
