steps:
  test-harbor-login:
    name: Test Harbor login from CI
    image: docker:cli
    when:
      event: [ push ]
      branch: [ master, develop ]
    environment:
      DOCKER_USERNAME:
        from_secret: DOCKER_USERNAME
      DOCKER_PASSWORD:
        from_secret: DOCKER_PASSWORD
    commands:
      - echo "USERNAME = $DOCKER_USERNAME"
      - echo "PASSWORD LENGTH = ${#DOCKER_PASSWORD}"
      - echo "$DOCKER_PASSWORD" | docker login harbor.dvirlabs.com -u "$DOCKER_USERNAME" --password-stdin

  build-image:
    name: Build & Push dvirlabs-landing
    image: woodpeckerci/plugin-kaniko
    when:
      branch: [ master, develop ]
      event: [ push, pull_request, tag ]
    settings:
      registry: harbor.dvirlabs.com
      repo: my-apps/${CI_REPO_NAME}
      dockerfile: Dockerfile
      context: .
      tags:
        - latest
        - ${CI_COMMIT_BRANCH}-${CI_COMMIT_SHA:0:7}
      username:
        from_secret: DOCKER_USERNAME
      password:
        from_secret: DOCKER_PASSWORD

  update-values:
    name: Update image tag in values.yaml
    image: alpine:3.19
    when:
      branch: [ master, develop ]
      event: [ push ]
    environment:
      GIT_USERNAME:
        from_secret: GIT_USERNAME
      GIT_TOKEN:
        from_secret: GIT_TOKEN
    commands:
      - apk add --no-cache git yq
      - git config --global user.name "woodpecker-bot"
      - git config --global user.email "ci@dvirlabs.com"
      - git clone "https://$${GIT_USERNAME}:$${GIT_TOKEN}@git.dvirlabs.com/dvirlabs/my-apps.git"
      - cd my-apps
      - |
        TAG="${CI_COMMIT_BRANCH}-${CI_COMMIT_SHA:0:7}"
        echo "💡 Setting image tag to: $TAG"
        yq -i ".image.tag = \"$TAG\"" manifests/${CI_REPO_NAME}/values.yaml
        git add manifests/${CI_REPO_NAME}/values.yaml
        git commit -m "image: update tag to $TAG" || echo "No changes"
        git push origin HEAD

  trigger-gitops-via-push:
    when:
      branch: [ master, develop ]
      event: [ push ]
    name: Trigger apps-gitops via Git push
    image: alpine/git
    environment:
      GIT_USERNAME:
        from_secret: GIT_USERNAME
      GIT_TOKEN:
        from_secret: GIT_TOKEN
    commands: |
      git config --global user.name "woodpecker-bot"
      git config --global user.email "ci@dvirlabs.com"
      git clone "https://$${GIT_USERNAME}:$${GIT_TOKEN}@git.dvirlabs.com/dvirlabs/apps-gitops.git"
      cd apps-gitops
      echo "# trigger at $(date) by $${CI_REPO_NAME}" >> .trigger
      git add .trigger
      git commit -m "ci: trigger apps-gitops build" || echo "no changes"
      git push origin HEAD
