name: Upload (AWS)

on:
  workflow_call:
    inputs:
      version:
        required: true
        type: string
      folder:
        required: true
        type: string
      trigger_type:
        required: true
        type: string

jobs:
  upload:
    name: Upload (AWS)

    runs-on: ubuntu-20.04

    steps:
    - name: Download all bundles
      uses: actions/download-artifact@v3

    - name: Calculate checksums
      run: |
        echo "::group::Move bundles to a single folder"
        mkdir bundles
        mv openttd-*/* bundles/
        echo "::endgroup::"

        cd bundles
        for i in $(ls openttd-*); do
          echo "::group::Calculating checksums for ${i}"
          openssl dgst -r -md5 -hex $i > $i.md5sum
          openssl dgst -r -sha1 -hex $i > $i.sha1sum
          openssl dgst -r -sha256 -hex $i > $i.sha256sum
          echo "::endgroup::"
        done

        # Some targets generate files that are meant for our-eyes-only.
        # They are stored in the "internal" folder, and contains bundles
        # for targets like Windows Store. No user has a benefit of knowing
        # they exist, hence: internal.
        if [ -e internal ]; then
          cd internal
          for i in $(ls openttd-*); do
            echo "::group::Calculating checksums for ${i}"
            openssl dgst -r -md5 -hex $i > $i.md5sum
            openssl dgst -r -sha1 -hex $i > $i.sha1sum
            openssl dgst -r -sha256 -hex $i > $i.sha256sum
            echo "::endgroup::"
          done
        fi

    - name: Upload bundles to AWS
      run: |
        aws s3 cp --recursive --only-show-errors bundles/ s3://${{ secrets.CDN_S3_BUCKET }}/${{ inputs.folder }}/${{ inputs.version }}/

        # We do not invalidate the CloudFront distribution here. The trigger
        # for "New OpenTTD release" first updated the manifest files and
        # creates an index.html. We invalidate after that, so everything
        # becomes visible at once.
      env:
        AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
        AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
        AWS_DEFAULT_REGION: ${{ secrets.AWS_REGION }}

    - name: Trigger 'New OpenTTD release'
      uses: peter-evans/repository-dispatch@v2
      with:
        token: ${{ secrets.DEPLOYMENT_TOKEN }}
        repository: OpenTTD/workflows
        event-type: ${{ inputs.trigger_type }}
        client-payload: '{"version": "${{ inputs.version }}", "folder": "${{ inputs.folder }}"}'
