name: Fleetbase GCP CI/CD

on:
  push:
    branches: [ "gcpdeploy/*" ]

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

env:
  PROJECT: ${{ vars.PROJECT }}
  REGISTRY: ${{ vars.REGISTRY }}
  SOCKETCLUSTER_HOST: ${{ vars.SOCKETCLUSTER_HOST }}
  API_HOST: ${{ vars.API_HOST }}
  K8S_CLUSTER_NAME: ${{ vars.K8S_CLUSTER_NAME }}
  K8S_CLUSTER_LOCATION: ${{ vars.K8S_CLUSTER_LOCATION }}
  GCP_WORKLOAD_IDENTITY_PROVIDER: ${{ vars.GCP_WORKLOAD_IDENTITY_PROVIDER }}
  GCP_SERVICE_ACCOUNT: ${{ vars.GCP_SERVICE_ACCOUNT }}
  GCP: "True" # switches docker builds to GCP-style registry

jobs:
  build_service:
    name: Build and Deploy the Service
    runs-on: ubuntu-latest
    permissions:
      id-token: write # This is required for requesting the JWT
      contents: read  # This is required for actions/checkout

    steps:
    - name: Checkout Code
      uses: actions/checkout@v3
      with:
        submodules: recursive

    - name: Set up Docker Buildx
      uses: docker/setup-buildx-action@v2

    - name: Set Dynamic ENV Vars
      run: |
          SHORT_COMMIT=$(echo $GITHUB_SHA | cut -c -8)
          echo "VERSION=${SHORT_COMMIT}" >> $GITHUB_ENV
          echo "STACK=$(basename $GITHUB_REF)" >> $GITHUB_ENV
          echo "REGISTRY_HOST=$(dirname $(dirname $REGISTRY))" >> $GITHUB_ENV

    - id: 'auth'
      name: 'Authenticate to Google Cloud'
      uses: 'google-github-actions/auth@v1'
      with:
        token_format: "access_token"
        create_credentials_file: true
        workload_identity_provider: ${{ env.GCP_WORKLOAD_IDENTITY_PROVIDER }}
        service_account: ${{ env.GCP_SERVICE_ACCOUNT }}

    - name: 'Set up Cloud SDK'
      uses: 'google-github-actions/setup-gcloud@v1'

    - id: 'get-credentials'
      uses: 'google-github-actions/get-gke-credentials@v1'
      with:
        cluster_name: ${{ env.K8S_CLUSTER_NAME }}
        location: ${{ env.K8S_CLUSTER_LOCATION }}

    - uses: 'docker/login-action@v3'
      with:
        registry: ${{ env.REGISTRY_HOST }}
        username: 'oauth2accesstoken'
        password: '${{ steps.auth.outputs.access_token }}'

    - name: Prepare Composer Auth Secret
      run: |
        if [[ -n "${{ secrets._GITHUB_AUTH_TOKEN }}" ]]; then
          echo '{"github-oauth": {"github.com": "'${{ secrets._GITHUB_AUTH_TOKEN }}'"}}' > composer-auth.json
        else
          echo '{}' > composer-auth.json
        fi

    - name: nullify ssm-parent config
      run: |
        # this is needed to disable ssm-parent, which is used on AWS
        echo > api/.ssm-parent.yaml

    - name: Build and Release
      uses: docker/bake-action@v2
      env: 
        REGISTRY: ${{ env.REGISTRY }}
        VERSION: ${{ env.VERSION }}
        CACHE: type=gha
      with:
        push: true
        files: |
          ./docker-bake.hcl

    - name: deploy with helm
      run: |
        helm upgrade -i fleetbase infra/helm -n ${{ env.PROJECT }}-${{ env.STACK }} --set image.repository=${{ env.REGISTRY }} --set image.tag=${{ env.VERSION }} --set 'api_host=${{ env.API_HOST }}' --set 'socketcluster_host=${{ env.SOCKETCLUSTER_HOST }}' --set 'ingress.annotations.kubernetes\.io/ingress\.global-static-ip-name=${{ env.PROJECT }}-${{ env.STACK }}' 

  build_frontend:
    name: Build and Deploy the Console
    needs: [build_service]
    runs-on: ubuntu-latest
    permissions:
      id-token: write # This is required for requesting the JWT
      contents: read  # This is required for actions/checkout

    steps:
    - name: Checkout
      uses: actions/checkout@v3
      with:
        submodules: true

    - name: Set Dynamic ENV Vars
      run: |
          SHORT_COMMIT=$(echo $GITHUB_SHA | cut -c -8)
          echo "VERSION=${SHORT_COMMIT}" >> $GITHUB_ENV
          echo "STACK=$(basename $GITHUB_REF)" >> $GITHUB_ENV

    - id: 'auth'
      name: 'Authenticate to Google Cloud'
      uses: 'google-github-actions/auth@v1'
      with:
        token_format: "access_token"
        create_credentials_file: true
        workload_identity_provider: ${{ env.GCP_WORKLOAD_IDENTITY_PROVIDER }}
        service_account: ${{ env.GCP_SERVICE_ACCOUNT }}

    - name: 'Set up Cloud SDK'
      uses: 'google-github-actions/setup-gcloud@v1'

    - name: Install Node.js
      uses: actions/setup-node@v3
      with:
        node-version: 16

    - uses: pnpm/action-setup@v2
      name: Install pnpm
      id: pnpm-install
      with:
        version: 8
        run_install: false

    - name: Get pnpm Store Directory
      id: pnpm-cache
      shell: bash
      run: |
        echo "STORE_PATH=$(pnpm store path)" >> $GITHUB_OUTPUT

    - uses: actions/cache@v3
      name: Setup pnpm Cache
      with:
        path: ${{ steps.pnpm-cache.outputs.STORE_PATH }}
        key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
        restore-keys: |
          ${{ runner.os }}-pnpm-store-

    - name: Check for _GITHUB_AUTH_TOKEN and create .npmrc
      run: |
        if [[ -n "${{ secrets._GITHUB_AUTH_TOKEN }}" ]]; then
          echo "//npm.pkg.github.com/:_authToken=${{ secrets._GITHUB_AUTH_TOKEN }}" > .npmrc
        fi
      working-directory: ./console

    - name: Install dependencies
      run: pnpm install
      working-directory: ./console

    - name: Build
      env:
        SOCKETCLUSTER_HOST: ${{ env.SOCKETCLUSTER_HOST }}
        SOCKETCLUSTER_SECURE: "true"
        SOCKETCLUSTER_PORT: "443"
        API_HOST: ${{ env.API_HOST }}
      run: |
        set -eu

        pnpm build --environment production
      working-directory: ./console

    - name: Deploy Console 🚀
      run: |
          set -eu

          gcloud app deploy --appyaml console/app.yaml console/dist
          # leave 2 versions
          gcloud app versions list --filter="traffic_split=0" --sort-by '~version' --format 'value(version.id)' | sed '1d' | xargs -r gcloud app versions delete
