resource "aws_iam_instance_profile" "catherine_fc_profile" {
  name_prefix = "${var.basename}-"
  role = aws_iam_role.instance.name
}

resource "aws_iam_role" "instance" {
    name = "${var.basename}-${terraform.workspace}"
    path = "/"

    assume_role_policy = <<EOF1
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": "sts:AssumeRole",
            "Principal": {
                "Service": "ec2.amazonaws.com"
            },
            "Effect": "Allow"
        }
    ]
}
EOF1

    tags = var.tags
}

resource "aws_iam_role_policy" "catherine_fc_autoscaling" {
    name = "catherine_fc_autoscaling_policy"
    role = aws_iam_role.instance.id
    policy = <<EOF2
{
    "Statement": [
        {
            "Action": [
                "autoscaling:UpdateAutoScalingGroup"
            ],
            "Effect": "Allow",
            "Resource": [
                "${var.asg_arn}"
            ]
        }
    ],
    "Version": "2012-10-17"
}
EOF2
}

resource "aws_iam_role_policy" "catherine_fc_ec2" {
    name = "catherine_fc_ec2_policy"
    role = aws_iam_role.instance.id
    policy = <<EOF4
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "ec2:DescribeInstances",
                "ec2:DescribeTags"
            ],
            "Effect": "Allow",
            "Resource": [
                "*"
            ]
        }
    ]
}
EOF4
}

resource "aws_iam_role_policy" "catherine_fc_s3" {
    name = "catherine_fc_s3_policy"
    role = aws_iam_role.instance.id
    policy = <<EOF5
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:GetObjectAcl",
                "s3:GetObject",
                "s3:ListBucket"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::catherine-fc-*"
            ]
        }
    ]
}
EOF5
}
