# This workflow push the branch on the staging server to be tested.
name: To-Staging

# Manual trigger
on: workflow_dispatch

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
      - uses: actions/checkout@v2

      # Create ssh key
      - name: Create SSH key
        run: |
          mkdir -p ~/.ssh/
          echo "$SSH_PRIVATE_KEY" > ../private.key
          eval "$(ssh-agent -s)"
          sudo chmod 600 ../private.key
          ssh-add ../private.key
          rm -rf ~/.ssh/known_hosts
          echo "$SSH_KNOWN_HOSTS" > ~/.ssh/known_hosts
        shell: bash
        env:
          SSH_PRIVATE_KEY: ${{secrets.SSH_PRIVATE_KEY}}
          SSH_KNOWN_HOSTS: ${{secrets.SSH_KNOWN_HOSTS}}
          SSH_KEY_PATH: ${{ github.workspace }}/../private.key

      - name: Create .env file
        env:
          HOST_URL: ${{ secrets.STAGING_HOST }}
          PLM_CLIENT_ID: ${{ secrets.STAGING_CLIENT_ID }}
        run: |
          cat << EOF > .env
          NEXT_PUBLIC_BASE_APP=/api
          NEXT_PUBLIC_HOST_URL=$HOST_URL
          NEXT_PUBLIC_PLM_HOST=https://prof.parlemonde.org
          NEXT_PUBLIC_CLIENT_ID=$PLM_CLIENT_ID
          EOF

      - name: Remove robots.txt
        run: |
          rm public/robots.txt

      - name: Add IP to AWS security group
        uses: sohelamin/aws-security-group-add-ip-action@master
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: eu-west-3
          aws-security-group-id: ${{ secrets.AWS_SECURITY_GROUP_ID_STAGING }}
          port: '22'
          description: 'GitHub Action'

      - name: Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@v1
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: eu-west-3

      - name: Login to Amazon ECR
        id: login-ecr
        uses: aws-actions/amazon-ecr-login@v1

      - name: Build, tag, and push image to Amazon ECR
        env:
          ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
        run: |
          docker build -t $ECR_REGISTRY/1village:staging .
          docker push $ECR_REGISTRY/1village:staging

      - name: Pull and run the docker image on the server
        run: ssh -i $SSH_KEY_PATH $server "ECR_REGISTRY=$ECR_REGISTRY IMAGE=$ECR_REGISTRY/1village:staging exec sh" < ./deploy.sh
        env:
          ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
          server: ${{secrets.STAGING_SERVER}}
          SSH_KEY_PATH: ${{ github.workspace }}/../private.key