name: Build & Release

on:
  push:
    branches: [main]
  workflow_dispatch:

concurrency:
  group: build
  cancel-in-progress: false

jobs:
  build:
    runs-on: ubuntu-latest
    env:
      REGISTRY: registry.digitalocean.com/lunarfront
      DOCKER_HOST: tcp://localhost:2375
      VERSION: 0.1.${{ github.run_number }}

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Login to DOCR
        run: echo "${{ secrets.DOCR_TOKEN }}" | docker login registry.digitalocean.com -u token --password-stdin

      - name: Build and push backend
        run: |
          SHA=$(git rev-parse --short HEAD)
          docker build \
            --build-arg APP_VERSION=$VERSION \
            -t $REGISTRY/lunarfront-app:$VERSION \
            -t $REGISTRY/lunarfront-app:$SHA \
            -t $REGISTRY/lunarfront-app:latest \
            -f Dockerfile .
          docker push $REGISTRY/lunarfront-app:$VERSION
          docker push $REGISTRY/lunarfront-app:$SHA
          docker push $REGISTRY/lunarfront-app:latest

      - name: Build and push frontend
        run: |
          SHA=$(git rev-parse --short HEAD)
          docker build \
            -t $REGISTRY/lunarfront-frontend:$VERSION \
            -t $REGISTRY/lunarfront-frontend:$SHA \
            -t $REGISTRY/lunarfront-frontend:latest \
            -f Dockerfile.frontend .
          docker push $REGISTRY/lunarfront-frontend:$VERSION
          docker push $REGISTRY/lunarfront-frontend:$SHA
          docker push $REGISTRY/lunarfront-frontend:latest

      - name: Install Helm
        run: curl -fsSL https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash

      - name: Package and push Helm chart
        run: |
          sed -i "s/^version:.*/version: $VERSION/" chart/Chart.yaml
          sed -i "s/^appVersion:.*/appVersion: \"$VERSION\"/" chart/Chart.yaml
          sed -i "s|tag: .*|tag: $VERSION|g" chart/values.yaml
          helm registry login registry.digitalocean.com -u token --password "${{ secrets.DOCR_TOKEN }}"
          helm package chart/
          helm push lunarfront-$VERSION.tgz oci://registry.digitalocean.com/lunarfront

      - name: Logout
        if: always()
        run: docker logout registry.digitalocean.com
