resource "aws_s3_bucket" "blog" {
	bucket = var.domain
	force_destroy = true
}


resource "aws_s3_bucket_acl" "blog_acl" {
	bucket = aws_s3_bucket.blog.id
	acl = "public-read"
}

resource "aws_s3_bucket_website_configuration" "blog_site" {
	bucket = aws_s3_bucket.blog.id
	index_document {
		suffix = "index.html"
	}
}

resource "aws_s3_bucket_cors_configuration" "blog_cors" {
	bucket = aws_s3_bucket.blog.id
	cors_rule {
		allowed_headers = ["*"]
		allowed_methods = ["GET"]
		allowed_origins = ["https://{var.domain}", "http://{var.domain}"]
		max_age_seconds = 3000
	}
}

resource "aws_iam_user" "blog_uploader" {
	name = "blog-uploader"
}

resource "aws_iam_user_policy_attachment" "blog_uploader_policy_attach" {
	user = aws_iam_user.blog_uploader.name
	policy_arn = aws_iam_policy.blog_bucket_policy.arn
}

resource "aws_iam_policy" "blog_bucket_policy" {
  name        = "blog-bucket-policy"
  path        = "/"
  description = "Allow "

  policy = jsonencode({
    "Version" : "2012-10-17",
    "Statement" : [
      {
        "Sid" : "VisualEditor0",
        "Effect" : "Allow",
        "Action" : [
          "s3:PutObject",
          "s3:GetObject",
          "s3:ListBucket",
          "s3:DeleteObject"
        ],
        "Resource" : [
	  "arn:aws:s3:::*/*",
          "arn:aws:s3:::{var.domain}"
        ]
      }
    ]
  })
}

resource "aws_iam_access_key" "blog_upload_key" {
	user = aws_iam_user.blog_uploader.name
}