variable "API_HOST" {
  description = "The host name of the device cloud"
}
variable "ASK_SKILL_ID" {
  description = "Your Alexa Skill ID"
}
resource "aws_iam_role" "iam_for_lambda" {
  name = "raspberry_iam_role"

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

resource "aws_lambda_function" "raspberry_led" {
  filename      = "/tmp/lambdaFunc.zip"
  function_name = "raspberry_led"
  role          = "${aws_iam_role.iam_for_lambda.arn}"
  handler       = "lambda_function/index.handler"
  source_code_hash = "${filebase64sha256("/tmp/lambdaFunc.zip")}"

  runtime = "nodejs10.x"

  environment {
    variables = {
      apihost = "${var.API_HOST}"
    }
  }
}

resource "aws_lambda_permission" "with_alexa" {
  statement_id  = "AllowExecutionFromAlexa"
  action        = "lambda:InvokeFunction"
  function_name = "${aws_lambda_function.raspberry_led.function_name}"
  principal     = "alexa-connectedhome.amazon.com"
  event_source_token = "${var.ASK_SKILL_ID}"
}

# This is to optionally manage the CloudWatch Log Group for the Lambda Function.
# If skipping this resource configuration, also add "logs:CreateLogGroup" to the IAM policy below.
resource "aws_cloudwatch_log_group" "raspberry_led_log_group" {
  name              = "/aws/lambda/${aws_lambda_function.raspberry_led.function_name}"
  retention_in_days = 3
}

# See also the following AWS managed policy: AWSLambdaBasicExecutionRole
resource "aws_iam_policy" "raspberry_led_lambda_logging" {
  name = "raspberry_led_lambda_logging"
  path = "/"
  description = "IAM policy for logging from a lambda"

  policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*",
      "Effect": "Allow"
    }
  ]
}
EOF
}

resource "aws_iam_role_policy_attachment" "raspberry_led_role_policy_attachment" {
  role = "${aws_iam_role.iam_for_lambda.name}"
  policy_arn = "${aws_iam_policy.raspberry_led_lambda_logging.arn}"
}
