AWSTemplateFormatVersion: "2010-09-09"
Description: >
  Cloud Cost Clinic kill-switch role (Autopilot tier, optional). This stack
  creates a customer-owned IAM role that lets Cloud Cost Clinic STOP (never
  terminate, never delete) EC2 instances that you have explicitly tagged
  ccc:killswitch=enabled, and only when your configured monthly spending cap
  is reached. Double opt-in by design: this role must exist AND each resource
  must carry the tag. Delete this stack at any time to disable the kill-switch.

Parameters:
  ScannerAwsAccountId:
    Type: String
    Description: AWS account ID that runs the Cloud Cost Clinic scanner backend.
    AllowedPattern: "^[0-9]{12}$"
    ConstraintDescription: Enter a 12-digit AWS account ID.

  ExternalId:
    Type: String
    Description: External ID assigned to your Cloud Cost Clinic product account.
    MinLength: 8
    MaxLength: 256
    AllowedPattern: "^[A-Za-z0-9+=,.@:_/-]+$"

Resources:
  CloudCostClinicKillSwitchRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: CloudCostClinicKillSwitchRole
      Description: Lets Cloud Cost Clinic stop explicitly opted-in (tagged) instances when your spending cap is reached. Stop only - never terminate or delete.
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              AWS: !Sub "arn:${AWS::Partition}:iam::${ScannerAwsAccountId}:root"
            Action: sts:AssumeRole
            Condition:
              StringEquals:
                sts:ExternalId: !Ref ExternalId
      Policies:
        - PolicyName: CloudCostClinicKillSwitchPolicy
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Sid: DescribeInstancesForTagLookup
                Effect: Allow
                Action:
                  - ec2:DescribeInstances
                Resource: "*"
              - Sid: StopOnlyExplicitlyTaggedInstances
                Effect: Allow
                Action:
                  - ec2:StopInstances
                Resource: !Sub "arn:${AWS::Partition}:ec2:*:${AWS::AccountId}:instance/*"
                Condition:
                  StringEquals:
                    aws:ResourceTag/ccc:killswitch: enabled

Outputs:
  KillSwitchRoleArn:
    Description: Role the Cloud Cost Clinic spending cap uses to stop opted-in instances.
    Value: !GetAtt CloudCostClinicKillSwitchRole.Arn

  WhatThisCanNeverDo:
    Description: Scope statement for review.
    Value: "Stop tagged EC2 instances only. No terminate, no delete, no RDS/EBS/network changes, no untagged resources."
