# Create Maxwell IAM user and attach Kinesis RW policy
resource "aws_iam_user" "switchboard_maxwell" {
  name          = "${var.environment}-switchboard-maxwell"
  force_destroy = true

  tags = {
    environment  = var.environment
    service_name = "switchboard-maxwell"
  }
}

resource "aws_iam_user_policy_attachment" "switchboard_maxwell_kinesis_attachment" {
  user       = aws_iam_user.switchboard_maxwell.name
  policy_arn = aws_iam_policy.kinesis_readwrite_policy.arn
}

resource "aws_iam_user_policy_attachment" "switchboard_maxwell_cloudwatch_attachment" {
  user       = aws_iam_user.switchboard_maxwell.name
  policy_arn = "arn:aws:iam::aws:policy/CloudWatchFullAccess"
}

data "aws_iam_policy_document" "kinesis_readwrite_policy" {
  statement {
    actions = [
      "kinesis:ListShards",
      "kinesis:ListStreams",
      "kinesis:GetShardIterator",
      "kinesis:GetRecords",
      "kinesis:DescribeStream",
      "kinesis:DescribeStreamConsumer",
      "kinesis:DescribeStreamSummary",
      "kinesis:PutRecord",
      "kinesis:PutRecords",
    ]

    # TF-UPGRADE-TODO: In Terraform v0.10 and earlier, it was sometimes necessary to
    # force an interpolation expression to be interpreted as a list by wrapping it
    # in an extra set of list brackets. That form was supported for compatibility in
    # v0.11, but is no longer supported in Terraform v0.12.
    #
    # If the expression in the following list itself returns a list, remove the
    # brackets to avoid interpretation as a list of lists. If the expression
    # returns a single list item then leave it as-is and remove this TODO comment.
    resources = [
      module.switchboard_kinesis_stream.kinesis_stream_arn,
    ]
  }
}

resource "aws_iam_policy" "kinesis_readwrite_policy" {
  name   = "${var.environment}-${var.service_name}-kinesis-RW-policy"
  policy = data.aws_iam_policy_document.kinesis_readwrite_policy.json
}

module "switchboard_maxwells_daemon" {
  source = "git@github.com:theorchard/terraform-vmware.git"

  vsphere_user     = var.vmware_user
  vsphere_password = var.vmware_password
  vsphere_server   = "ny-vsphere01.theorchard.local"

  vm_hostnames = [
    "qa-maxwells-switchboard01",
  ]

  vm_domain = "theorchard.local"

  vsphere_datacenter_name      = "ny-vsphere-dc"
  vsphere_datastore_name       = "nimble2-vol07"
  vsphere_compute_cluster_name = "ny-vsphere-cluster"
  vsphere_network_name         = "Server Network"
  vm_num_cpus                  = "2"
  vm_memory                    = "4096"
  chef_client_version          = "15.1.36"
}
