AWSTemplateFormatVersion: '2010-09-09'
Description: 'CloudFormation template to create an EC2 instance with Rclone installed'

Parameters:
  YourS3Bucket:
    Type: String
    Description: Specify the name of your destination Amazon S3 Bucket
  LatestAmiId:
    Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
    Default: '/aws/service/canonical/ubuntu/server/jammy/stable/current/arm64/hvm/ebs-gp2/ami-id'    
  InstanceType:
    Description: Select an instance type compatible with the Ubuntu based AMI Architecure and offered in the Region's Availability Zone. Refer to Blog instructions for more details.
    Type: String
    Default: m7g.medium
  KeyName:
    Description: Select an existing EC2 KeyPair to enable SSH access to the instance.
    Type: AWS::EC2::KeyPair::KeyName
  GDriveClientId:
    Description: Client ID for Rclone Google Drive remote configuration.
    Type: String
    NoEcho: true
  GDriveClientSecret:
    Description: Client Secret for Rclone Google Drive remote configuration.
    Type: String
    NoEcho: true
  SelfIP:
    Description: Your IP address for SSH access. Must be a valid IP CIDR range of the form x.x.x.x/x.
    Type: String
    Default: ''
  VpcId:
    Description: Select the VPC in which to create the EC2 instance.
    Type: AWS::EC2::VPC::Id
  SubnetId:
    Description: Select the Subnet in which to create the EC2 instance.
    Type: AWS::EC2::Subnet::Id
    

Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
      - Label:
          default: "EC2 Configuration"
        Parameters:
          - VpcId
          - SubnetId
          - InstanceType
          - LatestAmiId
          - KeyName
          - SelfIP
      - Label:
          default: "Rclone Google Drive Remote Configuration"
        Parameters:
          - GDriveClientId
          - GDriveClientSecret
      - Label:
          default: "Your Destination Amazon S3 Bucket"
        Parameters:
          - YourS3Bucket

    ParameterLabels:
      InstanceType:
        default: "EC2 instance type"
      KeyName:
        default: "EC2 key pair"
      SelfIP:
        default: "Your IP Address"
      VpcId:
        default: "VPC"
      SubnetId:
        default: "Subnet"
      GDriveClientId:
        default: "Client ID"
      GDriveClientSecret:
        default: "Client Secret"
      YourS3Bucket:
        default: "S3 Bucket Name"

Conditions:
  HasSelfIP: !Not [!Equals [!Ref 'SelfIP', '']]

Resources:

  myInstanceProfile:
    Type: 'AWS::IAM::InstanceProfile'
    Properties:
      Path: /
      Roles:
        - !Ref myEC2Role


  myEC2Role:
    Type: 'AWS::IAM::Role'
    Properties:
      ManagedPolicyArns:
        - 'arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore'
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service: ec2.amazonaws.com
            Action: 'sts:AssumeRole'      
      Policies:    
        - PolicyName: AllowReadWritePolicy
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - "s3:ListBucket*"
                  - "s3:ListAllMyBuckets"
                  - "s3:DeleteObject"
                  - "s3:GetObject"
                  - "s3:PutObject"
                  - "s3:PutObjectAcl"                  
                Resource:
                  - !Sub arn:${AWS::Partition}:s3:::${YourS3Bucket}/*      
                  - !Sub arn:${AWS::Partition}:s3:::${YourS3Bucket}     
              - Effect: Allow
                Action:
                  - "s3:ListAllMyBuckets"              
                Resource:
                  - !Sub arn:${AWS::Partition}:s3:::*            

  AccessKeySecret:
    Type: AWS::SecretsManager::Secret
    Properties:
      Name: !Sub 'rclone-secrets-${AWS::StackName}'
      SecretString: !Sub '{"GDriveClientId":"${GDriveClientId}", "GDriveClientSecret":"${GDriveClientSecret}"}'
      


  EC2Instance:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: !Ref 'InstanceType'
      IamInstanceProfile: !Ref myInstanceProfile
      SecurityGroupIds: [!Ref 'InstanceSecurityGroup']
      KeyName: !Ref 'KeyName'
      ImageId: !Ref LatestAmiId
      SubnetId: !Ref 'SubnetId'
      Tags:
        - Key: Name
          Value: Rclone Instance - GDrive to S3
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash
          sudo apt update
          sudo apt install -y curl unzip
          
          curl https://rclone.org/install.sh | sudo bash

          sleep 10
          
          # Create rclone configuration directory
          mkdir -p /home/ubuntu/.config/rclone

          # Write rclone configuration file
          cat > /home/ubuntu/.config/rclone/rclone.conf <<EOF
          
          [s3-remote]
          type = s3
          provider = AWS
          env_auth = true
          region = ${AWS::Region}

          [gdrive-remote]
          type = drive
          client_id = ${GDriveClientId}
          client_secret = ${GDriveClientSecret}
          scope = drive

          EOF

          chown -R ubuntu:ubuntu /home/ubuntu/.config/rclone
          sleep 10
        
        

      BlockDeviceMappings:
        - DeviceName: /dev/sda1
          Ebs:
            VolumeType: gp3
            VolumeSize: 25

  InstanceSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Allow all traffic from self IP and AWS IP range
      VpcId: !Ref 'VpcId'
      SecurityGroupIngress:
        - !If
          - HasSelfIP
          - Description: Inbound Rule from Self IP
            IpProtocol: tcp
            FromPort: 22
            ToPort: 22
            CidrIp: !Ref 'SelfIP'
          - !Ref 'AWS::NoValue'
      SecurityGroupEgress:
        - Description: Allow all outbound traffic
          IpProtocol: -1
          FromPort: -1
          ToPort: -1
          CidrIp: '0.0.0.0/0'

Outputs:
  InstanceId:
    Description: InstanceId of the newly created EC2 instance
    Value: !Ref 'EC2Instance'
  PublicIPv4Address:
    Description: Public IPv4 address of the newly created EC2 instance
    Value: !GetAtt 'EC2Instance.PublicIp'
  AccessKeySecretArn:
    Description: ARN of the Secrets Manager secret Google Drive Client ID and Client Secret
    Value: !Ref 'AccessKeySecret'