---
AWSTemplateFormatVersion: 2010-09-09
Description: Openvidu Server CE CloudFormation AMI template.

Mappings:
  AMIMAP:
    eu-west-1:
      AMI: AMIEUWEST1
    us-east-1:
      AMI: AMIUSEAST1

Resources:
  OpenviduServerCE:
    Type: 'AWS::EC2::Instance'
    Metadata:
      Comment: "Install OpenVidu Server CE"
      AWS::CloudFormation::Init:
        config:
          files:
            "/etc/cfn/cfn-hup.conf":
              content: !Sub |
                [main]
                stack=${AWS::StackId}
                region=${AWS::Region}
              mode: "000400"
              owner: "root"
              group: "root"
            "/etc/cfn/hooks.d/cfn-auto-reloader.conf":
              content: !Sub |
                [cfn-auto-reloader-hook]
                triggers=post.update
                path=Resources.OpenviduServerCE.Metadata.AWS::CloudFormation::Init
                action=/usr/local/bin/cfn-init -v --stack ${AWS::StackName} --resource OpenviduServerCE --region ${AWS::Region}
              mode: "000400"
              owner: "root"
              group: "root"
            "/usr/local/bin/installDockerAndDockerCompose.sh":
              content: |
                #!/bin/bash
                set -eu -o pipefail

                # Install Docker
                apt-get update && apt-get install -y \
                    apt-transport-https \
                    ca-certificates \
                    curl \
                    gnupg-agent \
                    software-properties-common

                curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
                echo \
                  "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \
                  $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null

                apt-get update && apt-get install -y \
                  docker-ce \
                  docker-ce-cli \
                  containerd.io

                # Install docker-compose v2
                LATEST_DOCKER_COMPOSE_VERSION=$(curl -sSL https://api.github.com/repos/docker/compose/tags | grep name | head -n1 | cut -d'"' -f4)

                OS="$(uname -s | awk '{print tolower($0)}')"
                ARCH="$(uname -m)"

                mkdir -p /usr/local/lib/docker/cli-plugins
                rm -f /usr/local/lib/docker/cli-plugins/docker-compose
                curl -SL "https://github.com/docker/compose/releases/download/${LATEST_DOCKER_COMPOSE_VERSION}/docker-compose-${OS}-${ARCH}" \
                  -o /usr/local/lib/docker/cli-plugins/docker-compose
                chmod +x /usr/local/lib/docker/cli-plugins/docker-compose
                ln -s /usr/local/lib/docker/cli-plugins/docker-compose /usr/local/bin

              mode: "000755"
              owner: "root"
              group: "root"
            "/usr/local/bin/installOpenviduCE.sh":
              content: |
                #!/bin/bash
                set -eu -o pipefail

                # Install openvidu-ce
                cd /opt
                curl https://s3-eu-west-1.amazonaws.com/aws.openvidu.io/install_openvidu_OPENVIDU_VERSION.sh | bash

                if [[ USE_MASTER_DOCKER_IMAGE == "true" ]]; then
                  pushd openvidu
                  # docker-compose.yml replace with master version
                  IMAGES="$(cat docker-compose.yml | grep 'image: openvidu/' | cut -d':' -f2 | sed -e 's/^[[:space:]]*//')"
                  for IMG in $IMAGES
                  do
                    sed -i "s|$IMG.*|$IMG:master|g" docker-compose.yml
                  done

                  # docker-compose.override.yml replace with master version
                  IMAGES="$(cat docker-compose.override.yml | grep 'image: openvidu/' | cut -d':' -f2 | sed -e 's/^[[:space:]]*//')"
                  for IMG in $IMAGES
                  do
                    sed -i "s|$IMG.*|$IMG:master|g" docker-compose.override.yml
                  done
                  popd
                fi

                # Define Installation Type
                sed -i "s/Installation Mode: On Premises/Installation Mode: Cloud Formation/" /opt/openvidu/docker-compose.yml

                # Configure crash report
                mkdir -p /opt/openvidu/kms-crashes
                sed -i "s/enabled=1/enabled=0/" /etc/default/apport
                echo "kernel.core_pattern=/opt/openvidu/kms-crashes/core_%e_%p_%u_%t" >> /etc/sysctl.conf
                sysctl --system
              mode: "000755"
              owner: "root"
              group: "root"
            "/usr/local/bin/getDockerImages.sh":
              content: !Sub |
                #!/bin/bash
                set -eu -o pipefail

                # Openvidu recording
                docker pull openvidu/openvidu-recording:OPENVIDU_RECORDING_DOCKER_TAG

                # OpenVidu CE images
                cd /opt/openvidu
                docker-compose pull
              mode: "000755"
              owner: "root"
              group: "root"
            "/usr/local/bin/testRecording.sh":
              content: |
                #!/bin/bash -x
                TEST_RECORDING_DIR="/opt/openvidu/test-recording"

                docker run -d --rm --name=test-recording -e URL=https://openvidu.io/ -v "${TEST_RECORDING_DIR}":/recordings openvidu/openvidu-recording:OPENVIDU_RECORDING_DOCKER_TAG

                # Wait to file to be created
                TIMEOUT_WAIT_FILE=30
                ELAPSED=0
                while [[ ! -f "${TEST_RECORDING_DIR}/video/video.mp4" ]] && [[ "${ELAPSED}" -lt "${TIMEOUT_WAIT_FILE}" ]]; do
                  sleep 1;
                  ELAPSED=$((ELAPSED+1))
                done

                # Sleep 30 seconds
                sleep 30

                # Clean test recording
                docker rm -f test-recording
                rm -rf "${TEST_RECORDING_DIR}"
              mode: "000755"
              owner: "root"
              group: "root"
    Properties:
      ImageId: !FindInMap [AMIMAP, !Ref 'AWS::Region', AMI]
      InstanceType: "t2.2xlarge"
      Tags:
        - Key: Name
          Value: !Ref AWS::StackName
      KeyName: AWS_KEY_NAME
      UserData:
        "Fn::Base64":
          !Sub |
            #!/bin/bash -x
            set -eu -o pipefail
            apt-get update && apt-get install -y \
                python3-pip \
                ec2-instance-connect
            pip3 install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-py3-latest.tar.gz

            cfn-init --region ${AWS::Region} --stack ${AWS::StackId} --resource OpenviduServerCE

            /usr/local/bin/installDockerAndDockerCompose.sh || { echo "[OpenVidu] error installing docker and compose"; exit 1; }

            /usr/local/bin/installOpenviduCE.sh || { echo "[OpenVidu] error installing OpenVidu CE"; exit 1; }

            /usr/local/bin/getDockerImages.sh || { echo "[OpenVidu] error getting docker images"; exit 1; }

            echo "@reboot /usr/local/bin/testRecording.sh >> /var/log/testRecording.log 2>&1" | crontab

            # sending the finish call
            /usr/local/bin/cfn-signal -e $? --stack ${AWS::StackId} --resource WaitCondition --region ${AWS::Region}

            # Cleaning the house
            shred -u /var/log/cloud-init-output.log
            shred -u /etc/ssh/*_key /etc/ssh/*_key.pub
            shred -u /usr/local/bin/installDockerAndDockerCompose.sh
            shred -u /usr/local/bin/installOpenviduCE.sh
            shred -u /usr/local/bin/getDockerImages.sh
            find /var/lib/cloud/instances/$(curl http://169.254.169.254/latest/meta-data/instance-id) -type f | xargs shred -u
            rm -rf /var/lib/cloud/instances/$(curl http://169.254.169.254/latest/meta-data/instance-id)

  WaitCondition:
    Type: AWS::CloudFormation::WaitCondition
    CreationPolicy:
      ResourceSignal:
        Timeout: PT20M
        Count: 1
