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


class BridgeAWSAutomation(BridgeAutomation):
    short_name = "bridge_aws"
    description = "Deploy Tor bridges on AWS EC2"
    provider = CloudProvider.AWS

    template_parameters = [
        "ssh_public_key_path",
        "ssh_private_key_path",
    ]

    template = """
    terraform {
      {{ backend_config }}
      required_providers {
        aws = {
          version = "~> 4.2.0"
        }
      }
    }

    locals {
      ssh_public_key  = "{{ ssh_public_key_path }}"
      ssh_private_key = "{{ ssh_public_key_path }}"
    }

    {% for resource in destroyed_resources %}
    {% set bridge, bridgeconf, account = resource %}
    provider "aws" {
      access_key = "{{ account.credentials['aws_access_key'] }}"
      secret_key = "{{ account.credentials['aws_secret_key'] }}"
      region     = "{{ account.credentials['aws_region'] }}"
      alias      = "account_{{ bridge.id }}"
    }
    {% endfor %}

    {% for resource in resources %}
    {% set bridge, bridgeconf, account = resource %}
    provider "aws" {
      access_key = "{{ account.credentials['aws_access_key'] }}"
      secret_key = "{{ account.credentials['aws_secret_key'] }}"
      region     = "{{ account.credentials['aws_region'] }}"
      alias      = "account_{{ bridge.id }}"
    }

    module "bridge_{{ bridge.id }}" {
      providers = {
        aws = aws.account_{{ bridge.id }}
      }
      source              = "{{ terraform_modules_path }}/terraform-aws-tor-bridge"
      ssh_public_key      = local.ssh_public_key
      ssh_private_key     = local.ssh_private_key
      contact_info        = "hi"
      namespace           = "{{ global_namespace }}"
      name                = "bridge"
      attributes          = ["{{ bridge.id }}"]
      distribution_method = "{{ bridgeconf.method }}"
    }

    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 %}
    """
