AWSTemplateFormatVersion: "2010-09-09"
Description: >
  Hosts Pyodide distributions for xlwings Lite. Creates an S3 bucket that
  serves files directly with CORS configured. Use the bucket URL
  as the value for the XLWINGS_PYODIDE_BASE_URL environment variable in your
  xlwings Lite ECS service. Optionally restricts access by source IP.

Parameters:
  AllowedIpRanges:
    Type: CommaDelimitedList
    Default: ""
    Description: >
      Optional comma-separated list of CIDR ranges allowed to read from the
      bucket (e.g. "203.0.113.0/24,198.51.100.0/22"). Leave empty for public
      read. Only set this if every user's browser reaches AWS from a known
      IP range (corporate VPN / office NAT).

Conditions:
  RestrictByIp: !Not [!Equals [!Join ["", !Ref AllowedIpRanges], ""]]

Resources:
  PyodideBucket:
    Type: AWS::S3::Bucket
    Properties:
      OwnershipControls:
        Rules:
          - ObjectOwnership: BucketOwnerEnforced
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: false
        IgnorePublicAcls: true
        RestrictPublicBuckets: false
      CorsConfiguration:
        CorsRules:
          - AllowedOrigins: ["*"]
            AllowedMethods: [GET, HEAD]
            AllowedHeaders: ["*"]
            MaxAge: 3000

  PyodideBucketPolicy:
    Type: AWS::S3::BucketPolicy
    Properties:
      Bucket: !Ref PyodideBucket
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - !If
            - RestrictByIp
            - Sid: ReadFromAllowedIps
              Effect: Allow
              Principal: "*"
              Action: s3:GetObject
              Resource: !Sub "${PyodideBucket.Arn}/*"
              Condition:
                IpAddress:
                  aws:SourceIp: !Ref AllowedIpRanges
            - Sid: PublicRead
              Effect: Allow
              Principal: "*"
              Action: s3:GetObject
              Resource: !Sub "${PyodideBucket.Arn}/*"

Outputs:
  BucketName:
    Description: s3 Bucket name where Pyodide files will be stored
    Value: !Ref PyodideBucket
  PyodideBaseUrl:
    Description: Set this as XLWINGS_PYODIDE_BASE_URL on your xlwings Lite ECS service
    Value: !Sub "https://${PyodideBucket.RegionalDomainName}"
