# state machine initiated with this policy/role.
data "aws_iam_policy_document" "assume_role_for_state_machine_policy" {
  statement {
    actions = [
      "sts:AssumeRole",
    ]

    principals {
      type = "Service"

      identifiers = [
        "states.${var.aws_region}.amazonaws.com",
      ]
    }
  }
}

resource "aws_iam_role" "state_machine_role" {
  name               = "${var.environment}-${var.state_machine_name}-state-machine-role"
  assume_role_policy = data.aws_iam_policy_document.assume_role_for_state_machine_policy.json
}

data "aws_iam_policy_document" "invoke_lambda_policy_for_state_machine" {
  statement {
    actions = [
      "lambda:InvokeFunction",
    ]
    resources = [
      module.lambda_ioc_sanitize.lambda_arn,
      module.lambda_ioc_update_waf_ipsets.lambda_arn,
      module.lambda_ioc_update_dns_firewall.lambda_arn,
      module.lambda_ioc_fargate_redeploy.lambda_arn,
    ]
  }
}

# Policy that gives the state machine role permission to start Distributed Map Executions
data "aws_iam_policy_document" "start_execution_state_machine_policy_doc" {
  statement {
    actions = [
      "states:StartExecution",
      "states:ListExecutions",
    ]

    resources = [
      aws_sfn_state_machine.state_machine.arn
    ]
  }
}

data "aws_iam_policy_document" "publish_sns_notification_policy" {
  statement {
    actions = [
      "sns:Publish",
    ]
    resources = [
      module.sfn_notifications.topic_arn,
      module.sfn_gsirt_notifications.topic_arn,
    ]
  }
}

data "aws_iam_policy_document" "cwlogs_policy" {
  statement {
    actions = [
      "logs:CreateLogStream",
      "logs:PutLogEvents",
    ]
    resources = [
      "${aws_cloudwatch_log_group.sfn_log_group.arn}:log-stream:*",
    ]
  }
  statement {
    actions = [
      "logs:CreateLogDelivery",
      "logs:GetLogDelivery",
      "logs:DescribeLogGroups",
      "logs:UpdateLogDelivery",
      "logs:DeleteLogDelivery",
      "logs:ListLogDeliveries",
      "logs:DescribeResourcePolicies",
      "logs:PutResourcePolicy",
    ]
    resources = ["*"]
  }
}

resource "aws_iam_policy" "start_execution_state_machine_policy" {
  name        = "StepFunctions-${var.environment}-${var.state_machine_name}-StartExecution"
  description = "Invoke Distributed Map Child State Machines"
  policy      = data.aws_iam_policy_document.start_execution_state_machine_policy_doc.json
}


# Policy that gives the state machine role permission to invoke lambdas
resource "aws_iam_role_policy" "invoke_lambda_role_policy" {
  name   = "${var.environment}-${var.state_machine_name}-invoke-lambda-role-policy"
  role   = aws_iam_role.state_machine_role.id
  policy = data.aws_iam_policy_document.invoke_lambda_policy_for_state_machine.json
}

resource "aws_iam_role_policy" "publish_sns_notification_role_policy" {
  name   = "${var.environment}-${var.state_machine_name}-publish-sns-notification-policy"
  role   = aws_iam_role.state_machine_role.id
  policy = data.aws_iam_policy_document.publish_sns_notification_policy.json
}

resource "aws_iam_role_policy" "cwlogs_role_policy" {
  name   = "${var.environment}-${var.state_machine_name}-cwlogs-policy"
  role   = aws_iam_role.state_machine_role.id
  policy = data.aws_iam_policy_document.cwlogs_policy.json
}

resource "aws_iam_role_policy_attachment" "execution_state_machine_attachment" {
  for_each = toset([
    aws_iam_policy.start_execution_state_machine_policy.arn,
  ])
  role       = aws_iam_role.state_machine_role.id
  policy_arn = each.key
}

resource "aws_sfn_state_machine" "state_machine" {
  name     = "${var.environment}-${var.state_machine_name}"
  role_arn = aws_iam_role.state_machine_role.arn
  definition = templatefile("${path.module}/ioc_block.json", {
    ioc_sanitize_arn                 = module.lambda_ioc_sanitize.lambda_arn,
    ioc_update_waf_ipsets_arn        = module.lambda_ioc_update_waf_ipsets.lambda_arn,
    ioc_update_dns_firewall_arn      = module.lambda_ioc_update_dns_firewall.lambda_arn,
    ioc_fargate_redeploy_arn         = module.lambda_ioc_fargate_redeploy.lambda_arn,
    bucket_name                      = data.aws_s3_bucket.pde_gsirt_bucket.bucket,
    update_waf_ipset_input           = jsonencode(local.update_waf_ipset_input)
    sns_notification_topic_arn       = module.sfn_notifications.topic_arn
    sns_gsirt_notification_topic_arn = module.sfn_gsirt_notifications.topic_arn
  })

  tags = {
    application_family = var.application_family
    environment        = var.environment
    service_name       = var.state_machine_name
    terraformed        = true
  }

  tracing_configuration {
    enabled = true
  }

  logging_configuration {
    log_destination        = "${aws_cloudwatch_log_group.sfn_log_group.arn}:*"
    include_execution_data = true
    level                  = "ERROR"
  }
}

resource "aws_cloudwatch_log_group" "sfn_log_group" {
  name              = "/aws/vendedlogs/states/${var.environment}-${var.state_machine_name}"
  retention_in_days = 365
}

module "sfn_notifications" {
  source                    = "git@github.com:theorchard/terraform-sns.git//?ref=3.1.0"
  environment               = var.environment
  application_family        = var.application_family
  sns_topic_name            = "${var.service_name}-notifications"
  sns_subscription_protocol = "email"
  sns_subscription_endpoint = var.notifications_slack_email_address
}

module "sfn_gsirt_notifications" {
  source                    = "git@github.com:theorchard/terraform-sns.git//?ref=3.1.0"
  environment               = var.environment
  application_family        = var.application_family
  sns_topic_name            = "${var.service_name}-gsirt-notifications"
  sns_subscription_protocol = "email"
  sns_subscription_endpoint = var.notifications_gsirt_email_address
}

data "aws_lambda_function" "datadog_lambda_function" {
  function_name = "DatadogLambdaFunction"
}

resource "aws_cloudwatch_log_subscription_filter" "datadog_lambda_function_log_filter" {
  name            = "${var.environment}-${var.service_name}-sfn-log-group-subscription-filter"
  log_group_name  = aws_cloudwatch_log_group.sfn_log_group.name
  filter_pattern  = ""
  destination_arn = data.aws_lambda_function.datadog_lambda_function.arn
  distribution    = "ByLogStream"
}

resource "datadog_monitor" "sns_monitor" {
  name    = "${upper(var.environment)} ${var.state_machine_name} SNS monitor"
  type    = "log alert"
  message = <<EOT
{{#is_alert}}SNS notification step produced error in ${var.environment}-${var.state_machine_name}.
[Link to the step function execution](https://${var.aws_region}.console.aws.amazon.com/states/home?region=${var.aws_region}#/v2/executions/details/{{log.attributes.execution_arn}})
Notify: ${var.slack_notification_channel} {{/is_alert}}
EOT

  query = "logs(\"service_name:${var.state_machine_name} environment:${var.environment} @details.resourceType:sns @details.resource:publish @status:error\").index(\"*\").rollup(\"count\").last(\"1h\") >= 1"

  monitor_thresholds {
    critical = 1
  }

  include_tags = true

  tags = [
    "environment:${var.environment}",
    "service_name:${var.state_machine_name}",
    "application_family:devops",
  ]
}

