Parameters:
  BucketName:
    Type: String
    Description: BucketName
    AllowedPattern: "[a-z][a-z0-9_-]*"
  UserName:
    Type: String
    Description: UserName
  RESKey:
    Type: String
    Description: RESKey
Resources:
  SFTPServer:
    Type: AWS::Transfer::Server
    Properties:
      EndpointType: PUBLIC

  SFTPServerS3Bucket:
    Type: AWS::S3::Bucket
    # DeletionPolicy: Retain
    Properties:
      BucketName: !Ref BucketName
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true

  # LambdaUsedToCleanUpArtifact:
  #   Type: Custom::cleanupbucket
  #   Properties:
  #     ServiceToken: !ImportValue EmptyS3BucketLambda
  #     BucketName: !Ref SFTPServerS3Bucket

  SFTPUserRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - transfer.amazonaws.com
            Action:
              - sts:AssumeRole
      Path: /
      Policies:
        - PolicyName: S3FullAccess
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - s3:ListAllMyBuckets
                  - s3:GetBucketLocation
                Resource: "*"
        - PolicyName: AllowListingOfUserFolder
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - s3:ListBucket
                Resource: !GetAtt SFTPServerS3Bucket.Arn
        - PolicyName: HomeDirObjectAccess
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - s3:PutObject
                  - s3:GetObject
                  - s3:GetObjectVersion
                  - s3:DeleteObject
                  - s3:DeleteObjectVersion
                Resource: !Sub "${SFTPServerS3Bucket.Arn}/*"

  TestUser:
    Type: AWS::Transfer::User
    Properties:
      ServerId: !GetAtt SFTPServer.ServerId
      UserName: !Ref UserName
      HomeDirectoryType: LOGICAL
      HomeDirectoryMappings:
        - Entry: /
          Target: !Sub "/${UserName}"
      # HomeDirectory: !Sub "/${SFTPServerS3Bucket}/${UserName}"

      Role: !GetAtt SFTPUserRole.Arn
      SshPublicKeys:
        - !Ref RESKey

Outputs:
  Hostname:
    Description: hostname
    Value: !Sub ${SFTPServer.ServerId}.server.transfer.${AWS::Region}.amazonaws.com

  CommonRole:
    Description: UserName
    Value: !Ref UserName
