name: CI

on:
  push:
    branches: [master]
    tags: ["v*"]
  pull_request:
    branches: [master]

env:
  CARGO_TERM_COLOR: always

jobs:
  check:
    name: Rust check
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Install system dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y --no-install-recommends \
            cmake g++ make pkg-config \
            libssl-dev libdlib-dev libblas-dev liblapack-dev

      - uses: dtolnay/rust-toolchain@stable
        with:
          components: rustfmt, clippy

      - uses: Swatinem/rust-cache@v2

      - name: Check formatting
        run: cargo fmt --check

      - name: Clippy
        run: cargo clippy -- -D warnings

      - name: Run tests
        run: cargo test

  frontend-check:
    name: Frontend check
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
          cache-dependency-path: frontend/package-lock.json

      - name: Install dependencies
        working-directory: frontend
        run: npm ci

      - name: Build
        working-directory: frontend
        run: npm run build

  docker-build:
    name: Build Docker image
    runs-on: ubuntu-latest
    needs: [check, frontend-check]
    if: github.event_name == 'push' && github.ref == 'refs/heads/master'
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@v4

      - uses: docker/setup-buildx-action@v3

      - uses: docker/build-push-action@v6
        with:
          context: .
          push: false
          cache-from: type=gha
          cache-to: type=gha,mode=max

  docker:
    name: Build and push Docker image
    runs-on: ubuntu-latest
    needs: [check, frontend-check]
    if: startsWith(github.ref, 'refs/tags/v')
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@v4

      - uses: docker/setup-buildx-action@v3

      - uses: docker/login-action@v3
        with:
          username: arnaudcayrol
          password: ${{ secrets.DOCKERHUB_TOKEN }}
          
      - uses: docker/metadata-action@v5
        id: meta
        with:
          images: arnaudcayrol/immich-selfie-timelapse
          tags: |
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=raw,value=latest,enable=${{ !contains(github.ref, '-') }}

      - uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
