data "aws_iam_policy_document" "assume_role_for_events_policy" {
  statement {
    sid = "AllowCWEServiceToAssumeRole"

    actions = [
      "sts:AssumeRole",
    ]

    principals {
      type = "Service"

      identifiers = [
        "events.amazonaws.com",
      ]
    }
  }
}

#  Policy for starting execution initiated by a CloudWatch rule.
data "aws_iam_policy_document" "start_execution_policy" {
  statement {
    actions = [
      "states:StartExecution",
    ]

    resources = [
      "${aws_sfn_state_machine.state_machine_v2.id}",
    ]
  }
}

# CloudWatch event rule role for starting execution
resource "aws_iam_role" "execute_state_machine_role" {
  name               = "${var.environment}_execute_assets_transcoding_state_machine_role"
  assume_role_policy = "${data.aws_iam_policy_document.assume_role_for_events_policy.json}"
}

resource "aws_iam_role_policy" "start_execution_role_policy" {
  name   = "${var.environment}_start_assets_transcoding_state_machine_execution_role_policy"
  role   = "${aws_iam_role.execute_state_machine_role.id}"
  policy = "${data.aws_iam_policy_document.start_execution_policy.json}"
}

data "template_file" "raw_asset_event_definition" {
  template = "${file("${path.module}/${var.cloudwatch_event_rule_pattern_file}")}"

  vars {
    observed_bucket_name = "${var.raw_assets_bucket}"
  }
}

# Event rule for new raw assets.
resource "aws_cloudwatch_event_rule" "raw_asset_event_rule" {
  name          = "${var.environment}_raw_asset_rule"
  description   = "The CloudWatch event rule for put object events on the raw assets bucket"
  event_pattern = "${data.template_file.raw_asset_event_definition.rendered}"
  role_arn      = "${aws_iam_role.execute_state_machine_role.arn}"
}

resource "aws_cloudwatch_event_target" "state_machine_target" {
  rule      = "${aws_cloudwatch_event_rule.raw_asset_event_rule.name}"
  role_arn  = "${aws_iam_role.execute_state_machine_role.arn}"
  target_id = "${var.environment}_state_machine_target_rule_target"
  arn       = "${aws_sfn_state_machine.state_machine_v2.id}"
}
