---
kind: pipeline
type: docker
name: default

steps:
  # Step 1: Check if Docker image for current version already exists
  - name: check-version
    image: docker:24
    environment:
      DOCKER_HOST: unix:///var/run/docker.sock
    commands:
      - apk add --no-cache git
      - git fetch --tags
      - LATEST_TAG=$(git describe --tags --abbrev=0)
      - echo "Latest Git tag: $LATEST_TAG"
      - |
        if docker image inspect apps/homepage:$NEW_VERSION > /dev/null 2>&1; then
          echo "Docker image apps/homepage:$NEW_VERSION already exists — skipping build"
          exit 0
        else
          echo "Docker image apps/homepage:$NEW_VERSION not found — building..."
        fi

  # Step 2: Build Docker image with dynamic Git tag
  - name: build-image
    image: docker:24
    environment:
      DOCKER_HOST: unix:///var/run/docker.sock
    commands:
      - IMAGE_TAG=${DRONE_TAG:-latest}
      - echo "Building Docker image apps/homepage:$IMAGE_TAG ..."
      - docker build -t apps/homepage:$IMAGE_TAG .

  # Step 3: Stop old container if exists
  - name: stop-old
    image: docker:24
    environment:
      DOCKER_HOST: unix:///var/run/docker.sock
    commands:
      - IMAGE_TAG=${DRONE_TAG:-latest}
      - echo "Stopping old container..."
      - docker rm -f homepage || true

  # Step 4: Run container with dynamic tag
  - name: run-container
    image: docker:24
    environment:
      DOCKER_HOST: unix:///var/run/docker.sock
    commands:
      - IMAGE_TAG=${DRONE_TAG:-latest}
      - echo "Starting container apps/homepage:$IMAGE_TAG ..."
      - docker run -d \
          --name homepage \
          -p 3001:3000 \
          -e NODE_ENV=production \
          apps/homepage:$IMAGE_TAG

# Trigger pipeline on Git tags
trigger:
  event:
    - push
    - tag
