name: Deploy server
on:
  push:
    branches:
      - dev
    tags:
      - "[v]?[0-9]+.[0-9]+.[0-9]+*"
  workflow_dispatch:
    inputs:
      environment:
        description: "Environment"
        required: true
        default: "nightly"
        type: choice
        options:
        - nightly
        - stable

concurrency:
  group: ${{ github.workflow }}
  cancel-in-progress: false

jobs:  
  deploy:
    runs-on: ubuntu-latest
    env:
      DATA_ENV: ${{ github.event.inputs.environment || 'nightly' }}
    permissions:
      id-token: write
      contents: read
    
    steps:      
      - name: Manipulate Environment
        id: manipulate
        run: |
          if [ "${{ github.event_name }}" = "push" ] && [ "$GITHUB_REF_NAME" = "dev" ]; then
            echo "env=nightly" >> $GITHUB_OUTPUT
          elif [ "${{ github.event_name }}" = "push" ] && [[ "${{ github.ref }}" = "refs/tags/"* ]]; then
            echo "env=stable" >> $GITHUB_OUTPUT
          elif [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
            echo "env=${{ env.DATA_ENV }}" >> $GITHUB_OUTPUT
          else
            echo "Operation not permitted"
            exit 1
          fi

      - name: Wait for test workflow to succeed
        if: github.event_name == 'push'
        uses: lewagon/wait-on-check-action@v1.3.1
        with:
          ref: ${{ github.ref }}
          # Have to specify '(notary)', as we are using matrix for build_and_test job in ci.yml, else it will fail, more details [here](https://github.com/lewagon/wait-on-check-action#check-name)
          check-name: 'Build and test (notary)'
          repo-token: ${{ secrets.GITHUB_TOKEN }}
          # How frequent (in seconds) this job will call GitHub API to check the status of the job specified at 'check-name'
          wait-interval: 60

      - name: Checkout
        uses: actions/checkout@v4
        with:
          persist-credentials: false
          
      - name: Configure AWS Credentials
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::490752553772:role/tlsn-deploy-slc
          role-duration-seconds: 1800
          aws-region: eu-central-1

      - name: Install stable rust toolchain
        uses: dtolnay/rust-toolchain@stable
        with:
          toolchain: stable
          components: clippy

      - name: Use caching
        uses: Swatinem/rust-cache@v2.5.0
        with:
          workspaces: ${{ matrix.package }} -> target

      - name: Cargo build
        run: |
          .github/scripts/build-server.sh ${{ steps.manipulate.outputs.env }}

      - name: Trigger Deployment
        run: |
          .github/scripts/deploy-server.sh ${{ steps.manipulate.outputs.env }} $GITHUB_REF_NAME

      - name: Modify Proxy
        if: ${{ steps.manipulate.outputs.env == 'stable' }}
        run: |
          .github/scripts/modify-proxy.sh
