# Flow logs need to be created per VPC, but we need a role
resource "aws_cloudwatch_log_group" "vpc_flow_logs" {
  name = "vpc_flow_logs"
  retention_in_days = 7
  kms_key_id = var.cloudtrail_key_arn
  tags = merge(var.standard_tags, var.tags)
}

resource "aws_iam_role" "flowlogs" {
  name = "flowlogs"
  path = "/aws_services/"
  tags = merge(var.standard_tags, var.tags)

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": "vpc-flow-logs.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
EOF
}

resource "aws_iam_role_policy" "flowlogs" {
  name = "flowlogs"
  role = aws_iam_role.flowlogs.id

  policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents",
        "logs:DescribeLogGroups",
        "logs:DescribeLogStreams"
      ],
      "Effect": "Allow",
      "Resource": "*"
    }
  ]
}
EOF
}

# Spit vpc flow logs to splunk
module "kinesis_firehose" {
  source = "../../thirdparty/terraform-aws-kinesis-firehose-splunk"
  region = var.aws_region
  arn_cloudwatch_logs_to_ship = "arn:${var.aws_partition}:logs:${var.aws_region}::log-group:/vpc_flow_logs/*"
  name_cloudwatch_logs_to_ship = "vpc_flow_logs"
  hec_token = var.aws_flowlogs_hec_token
  hec_url = "https://${var.hec_pub_ack}:8088"
  firehose_name = "vpc_flow_logs_to_splunk"
  tags = merge(var.standard_tags, var.tags)
  cloudwatch_log_retention = 30 # keep kinesis logs this long
  log_stream_name = "SplunkDelivery_VPCFlowLogs"
  s3_bucket_name = "kinesis-flowlogs-${var.aws_account_id}-${var.aws_region}"
  s3_bucket_block_public_access_enabled = 1
  s3_backup_mode = "FailedEventsOnly"
  s3_expiration = 30
}

