on:
  push:
  workflow_dispatch:
    inputs:
      build:
        description: "Build container"
        required: false
        default: false
        type: boolean

jobs:
  build:
    runs-on: container
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Get the version from git
        id: version
        run: echo "version=$(git describe --dirty --tags)" >> $GITHUB_OUTPUT

      - name: Check if the container should be built
        id: builder
        env:
          RUN: ${{ toJSON(inputs.build || !contains(steps.version.outputs.version, '-')) }}
        run: |
          echo "run=$RUN" >> $GITHUB_OUTPUT
          echo "Run build: $RUN"

      - name: Info - version and if the image container should be built
        env:
          VERSION: ${{ steps.version.outputs.version }}
          RUN: ${{ steps.builder.outputs.run }}
          FORCE: ${{ toJSON(inputs.build) }}
        run: |
          echo "Version $VERSION, force (manual input): $FORCE, run the build: $RUN"

      - uses: pnpm/action-setup@v4
        name: Install pnpm
        with:
          run_install: false

      - name: Install Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: "pnpm"

      - name: Install dependencies
        run: pnpm install

      - name: Build package (transpile ts => js)
        run: ng build

      #- name: Git unshallow - get all history from Git to get the tag for the computation of the version
      #  if: ${{ inputs.build }}
      #  run: git pull --unshallow

      - name: Build container
        if: fromJSON(steps.builder.outputs.run)
        uses: actions/buildah-build@v1
        with:
          image: treetrail-frontend
          oci: true
          labels: treetrail-frontend
          tags: ${{ steps.version.outputs.version }}
          containerfiles: |
            ./Containerfile

      - name: Workaround for bug of podman-login
        if: fromJSON(steps.builder.outputs.run)
        run: |
          mkdir -p $HOME/.docker
          echo "{ \"auths\": {} }" > $HOME/.docker/config.json

      - name: Log in to container registry (with another workaround)
        if: fromJSON(steps.builder.outputs.run)
        uses: actions/podman-login@v1
        with:
          registry: ${{ vars.REGISTRY }}
          username: ${{ secrets.REGISTRY_USER }}
          password: ${{ secrets.REGISTRY_PASSWORD }}
          auth_file_path: /tmp/auth.json

      - uses: actions/push-to-registry@v2
        if: fromJSON(steps.builder.outputs.run)
        with:
          registry: "docker://${{ vars.REGISTRY }}"
          image: treetrail-frontend
          tags: ${{ steps.version.outputs.version }}
