# Assume role policy used by airflow scheduler agent role
data "aws_iam_policy_document" "airflow_assume_role_policy" {
    statement {
        actions = ["sts:AssumeRole"]

        principals {
            type = "AWS"

            identifiers = [
                "arn:aws:iam::${module.aws_accounts.all_accounts["prod"]}:role/${var.environment}-abacus-airflow-airflow-execution-role",
            ]
        }
    }
}

resource "aws_iam_role" "airflow_run_role" {
    name                  = "${var.environment}-${var.service_name}-airflow-run-role"
    force_detach_policies = true
    assume_role_policy    = data.aws_iam_policy_document.airflow_assume_role_policy.json

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


data "aws_iam_policy_document" "run_task_policy_document" {
    statement {
        effect = "Allow"
        actions = [
            "ec2:DescribeSecurityGroups",
            "ec2:DescribeSubnets",
            "ec2:DescribeVpcs",
            "ecs:DescribeTasks"
        ]
        resources = ["*"]
    }

    statement {
        effect = "Allow"
        actions = [
            "ecs:RunTask",
            "ecs:StartTask"
        ]
        resources = [
            "${module.ecs_abacus_extract_sales_fargate_environment.fargate_task_definition_arn_without_revision}:*",
            module.ecs_abacus_extract_sales_fargate_environment.fargate_cluster_arn
        ]
    }

    statement {
        effect = "Allow"
        actions = [
            "ecs:TagResource",
        ]
        resources = ["*"]
        condition {
            test     = "StringEquals"
            variable = "ecs:CreateAction"
            values = [
                "RunTask",
                "StartTask",
            ]
        }
  }

    statement {
        effect  = "Allow"
        actions = ["iam:PassRole"]
        condition {
            test     = "StringLike"
            variable = "iam:PassedToService"
            values   = ["ecs-tasks.amazonaws.com"]
        }
        resources = [
            module.ecs_abacus_extract_sales_fargate_environment.fargate_task_iam_role_arn,
            module.ecs_abacus_extract_sales_fargate_environment.fargate_task_iam_execution_role_arn
        ]
    }
}

resource "aws_iam_policy" "airflow_run_policy" {
    name   = "${var.environment}-${var.service_name}-run-policy"
    policy = data.aws_iam_policy_document.run_task_policy_document.json

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

resource "aws_iam_role_policy_attachment" "airflow_run_policy_attachment" {
    role       = aws_iam_role.airflow_run_role.id
    policy_arn = aws_iam_policy.airflow_run_policy.arn
}
