AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Parameters:
  Environment:
    Type: String
    AllowedValues:
      - dev
      - prod
    Description: The environment (e.g., dev or prod)
  TencyZipsBucket:
    Type: String
    Description: Where tency uploads their original zips
  TencyJamTracksBucket:
    Type: String
    Description: Where we unzip their zipped files
  EfsId:
    Type: String
    Description: The ID of the EFS to use for scratch
  VpcId:
    Type: String
    Description: The ID of the VPC where the Lambda function and EFS are deployed.
  SubnetIds:
    Type: CommaDelimitedList
    Description: The IDs of the subnets where the Lambda function will be deployed.
  SgIds:
    Type: CommaDelimitedList
    Description: The Id Of the security group
  MountPath:
    Type: String
    Description: The path to mount the EFS volume into the lamdda
  JamTrackContainerPath:
    Type: String
    Description: The local or container registry path to the jamtrack container
  DbHost:
    Type: String
    Description: potsgresql host
  DbUser:
    Type: String
    Description: postgresql user
  DbPass:
    Type: String
    Description: postgresql pass
  DbName:
    Type: String
    Description: db name
  AwsBucket:
    Type: String
    Description: aws bucket
  AwsBucketPublic:
    Type: String
    Description: aws bucket public

Globals:
  Function:
    #Runtime: ruby3.3
    CodeUri: ./
    Architectures:
      - x86_64
    #Handler: app.lambda_handler

Resources:
  TencyUnzipFunction:
    Type: AWS::Serverless::Function
    Properties:
      #Handler: lambdas/unzipper/app.lambda_handler
      #Runtime: ruby3.3
#      Layers:
#        - !Ref AssetLayer
#        - !Ref PGLayer
#        - !Ref SharedLayer
      MemorySize: 500
      Timeout: 900
      PackageType: Image
      ImageUri: !Ref JamTrackContainerPath
      FileSystemConfigs:
        - Arn: !GetAtt EFSMountTarget.Arn
          LocalMountPath: /mnt/efs
      VpcConfig:
        SubnetIds: !Ref SubnetIds
        SecurityGroupIds: !Ref SgIds
      Role: !GetAtt ZipExtractorFunctionRole.Arn
      Environment:
        Variables:
          ENV: !Ref Environment
          DB_HOST: !Ref DbHost
          DB_USER: !Ref DbUser
          DB_PASS: !Ref DbPass
          DB_NAME: !Ref DbName
          TENCY_ZIPS_BUCKET: !Ref TencyZipsBucket
          TENCY_JAMTRACKS_BUCKET: !Ref TencyJamTracksBucket
          AWS_BUCKET: !Ref AwsBucket
          AWS_BUCKET_PUBLIC: !Ref AwsBucketPublic
          FFMPEG_PATH: /opt/bin/ffmpeg
          FFMPEG_PATH_MP3: /opt/bin/ffmpeg
          JMEP_DIR: /var/task/shared/jmep
          END_ON_FAIL: 1
          MOUNT_PATH: !Ref MountPath
#  AssetLayer:
#    Type: AWS::Serverless::LayerVersion
#    Properties:
#      LayerName: asset-layer
#      ContentUri: s3://jamkazam-repo/lambda-assets/jamtrack-importer-assets.zip
#      ContentUri: ./assets/assets.zip
#      CompatibleRuntimes:
#        - ruby3.3
#  PGLayer:
#    Type: AWS::Serverless::LayerVersion
#    Properties:
#      CompatibleRuntimes:
#        - ruby3.3
#      ContentUri: 'pg_layer'
#    Metadata:
#      BuildMethod: makefile

#  SharedLayer:
#    Type: AWS::Serverless::LayerVersion
#    Properties:
#      LayerName: shared-layer
#      Description: Shared code layer for Lambda functions
#      ContentUri: shared/
#      CompatibleRuntimes:
#        - ruby3.3

  # IAM Role for Lambda
  ZipExtractorFunctionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - !Ref EFSFullAccessPolicy
        - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
      Policies:
        - PolicyName: S3AccessPolicy
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - "s3:ListBucket"
                  - "s3:GetObject"
                Resource:
                  - !Sub "arn:aws:s3:::${TencyZipsBucket}"
                  - !Sub "arn:aws:s3:::${TencyZipsBucket}/*"
              - Effect: Allow
                Action:
                  - "s3:ListBucket"
                  - "s3:GetObject"
                  - "s3:PutObject"
                Resource:
                  - !Sub "arn:aws:s3:::${TencyJamTracksBucket}"
                  - !Sub "arn:aws:s3:::${TencyJamTracksBucket}/*"
        - PolicyName: VPCNetworkingPolicy
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - "ec2:CreateNetworkInterface"
                  - "ec2:DescribeNetworkInterfaces"
                  - "ec2:DeleteNetworkInterface"
                Resource: "*"  # You can narrow this down by specifying resources if needed 
  # Managed Policy for EFS Access
  EFSFullAccessPolicy:
    Type: AWS::IAM::ManagedPolicy
    Properties:
      Description: EFS full access for Lambda
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Action:
              - "elasticfilesystem:ClientMount"
              - "elasticfilesystem:ClientWrite"
            Resource: !GetAtt EFSMountTarget.Arn


  # EFS Mount Target
#  MountTaget1:
#    Type: AWS::EFS::MountTarget
#    Properties:
#      FileSystemId: !Ref EfsId
#      SubnetId: !Select [0, !Ref SubnetIds]  # us-east1
#      SecurityGroups: [!Ref SgId]

  # EFS Mount Target for Lambda
  EFSMountTarget:
    Type: AWS::EFS::AccessPoint
    Properties:
      FileSystemId: !Ref EfsId
      PosixUser:
        Uid: "1000"
        Gid: "1000"
      RootDirectory:
        CreationInfo:
          OwnerUid: "1000"
          OwnerGid: "1000"
          Permissions: "0777"
        Path: !Ref MountPath
