on:
  pull_request:

concurrency:
  group: ${{ github.event.number }}
  cancel-in-progress: true

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
    - name: inject slug/short variables
      uses: rlespinasse/github-slug-action@v3.x

    - name: set STAGE variable in environment for next steps
      run: echo "STAGE=pr-${{ github.event.number }}-${{ env.GITHUB_HEAD_REF_SLUG }}" >> $GITHUB_ENV

    - name: Create Deployment
      uses: bobheadxi/deployments@v1
      id: deployment
      with:
        step: start
        token: ${{ github.token }}
        env: ${{ env.STAGE }}
        ref: ${{ github.head_ref }}
        no_override: false
        transient: true

    - uses: actions/checkout@v3

    - name: Setup Hugo
      uses: peaceiris/actions-hugo@v2
      with:
        hugo-version: 'latest'

    - name: Staging configuration
      run: |
        sed -i -e 's/^baseURL\s*=.*$/baseUrl = ""/i' config.toml
        echo "relativeurls = true" >>config.toml
      working-directory: src

    - name: Build
      run: hugo -s src -d ../public

    - 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: us-east-1

    - uses: actions/setup-node@v3
      with:
        node-version: 14
    - name: install node dependencies
      uses: bahmutov/npm-install@v1
      with:
        working-directory: .cdk

    - name: deploy the stack on AWS
      id: cdk_deploy
      run: yarn deploy
      working-directory: .cdk

    - name: Seal Deployment
      uses: bobheadxi/deployments@v1
      if: always()
      with:
        step: finish
        token: ${{ github.token }}
        status: ${{ job.status }}
        deployment_id: ${{ steps.deployment.outputs.deployment_id }}
        env: ${{ env.STAGE }}
        env_url: ${{ steps.cdk_deploy.outputs.env_url }}
