import * as cdk from "@aws-cdk/core";
import * as iam from "@aws-cdk/aws-iam";
import * as accountID from "../../account-ids";

/**
 * GrafanaPermissions contains the IAM role and policy needed by Grafana to use
 * Autohost's CloudWatch as a data source.
 */
export class GrafanaPermissions extends cdk.Construct {
  constructor(scope: cdk.Construct, id: string) {
    super(scope, id);

    // Grafana assumes this role to gain access to our CloudWatch metrics.
    const grafanaCloudWatchRole = new iam.Role(this, "GrafanaCloudWatchRole", {
      roleName: "grafana-cloudwatch-read-only",
      assumedBy: new iam.CompositePrincipal(
        new iam.ArnPrincipal(
          `arn:aws:iam::${accountID.twitchGrafanaProd}:role/grafana-production`
        ),
        new iam.ArnPrincipal(
          `arn:aws:iam::${accountID.twitchGrafanaDev}:role/grafana-development`
        ),
        new iam.ArnPrincipal(
          `arn:aws:iam::${accountID.twitchCentralAWS}:role/grafana-production`
        )
      )
    });

    // The IAM policy that allows Grafana to fetch our CloudWatch metrics.
    new iam.Policy(this, "GrafanaCloudWatchPolicy", {
      policyName: "grafana-cloudwatch-access-policy",
      statements: [
        new iam.PolicyStatement({
          actions: [
            "cloudwatch:DescribeAlarmsForMetric",
            "cloudwatch:GetMetricData",
            "cloudwatch:GetMetricStatistics",
            "cloudwatch:ListMetrics"
          ],
          resources: ["*"]
        }),
        new iam.PolicyStatement({
          actions: [
            "ec2:DescribeInstances",
            "ec2:DescribeTags",
            "ec2:DescribeRegions"
          ],
          resources: ["*"]
        }),
        new iam.PolicyStatement({
          actions: ["tag:GetResources"],
          resources: ["*"]
        })
      ],
      roles: [grafanaCloudWatchRole]
    });
  }
}
