# Panorama
resource "aws_placement_group" "panorama_group" {
  name = "Panorama Placement Group"
  strategy = "spread"
}

resource "aws_instance" "panorama" {
  count = var.panorama_count
  ami = lookup(var.panorama_ami, var.aws_region)
  availability_zone = var.azs[count.index % 2]
  placement_group = aws_placement_group.panorama_group.id
  tenancy = "default"
  ebs_optimized = true
  disable_api_termination = var.instance_termination_protection
  instance_initiated_shutdown_behavior = "stop"
  instance_type = var.panorama_instance_type
  key_name = var.panorama_key_name
  monitoring = false
  vpc_security_group_ids = var.panorama_security_group_ids
  subnet_id = var.subnet_id_map["management"][count.index % 2]
  #associate_public_ip_address = true # causes a recreate on apply if you set this!
  private_ip = cidrhost(var.subnet_cidr_map["management"][count.index % 2], 5 + (count.index % 2))
  source_dest_check = true

  tags = merge(
    var.standard_tags,
    var.tags,
    { Name = "xdr-panorama-${count.index}" }
  )

  root_block_device {
    volume_type = "gp2"
    volume_size = "81"
    delete_on_termination = true
    encrypted = true
    kms_key_id = var.ebs_key
  }

  # The provisioner doesn't do anything
  #connection {
  #  type = "ssh"
  #  user = "admin"
  #  private_key = file("~/.ssh/id_rsa") # Use your private key
  #  host = aws_eip.management_eip[count.index].public_ip
  #} 
  #
  #provisioner "remote-exec" {
  #  # Used by a provisioner
  #
  #  inline = [
  #    "set mgt-config users admin password",
  #    "testme",
  #    "testme",
  #    "commit"
  #  ]
  #  on_failure = continue
  #}
}

# EIP for Management Interface, declared separately so they're easier to preserve
resource "aws_eip" "management_eip" {
    count = var.panorama_count
    vpc = true
}

resource "aws_eip_association" "eip_assoc" {
  count = var.panorama_count
  instance_id   = aws_instance.panorama[count.index].id
  allocation_id = aws_eip.management_eip[count.index].id
  private_ip_address = cidrhost(var.subnet_cidr_map["management"][count.index % 2], 5 + (count.index % 2))
}

