matrix:
  include:
    - LEDGER_IMAGE_PATH: ledger/service
      LEDGER_DOCKERFILE: ci/prod/compose/ledger.dockerfile
      LEDGER_MONGO_SECRET_PATH: sendico/db
      LEDGER_ENV: prod

when:
  - event: push
    branch: main
    path:
      include: 
        - api/ledger/**
        - api/proto/**
        - api/pkg/**
      ignore_message: '[rebuild]'

steps:
  - name: version
    image: alpine:latest
    commands:
      - set -euo pipefail 2>/dev/null || set -eu
      - apk add --no-cache git
      - GIT_REV="$(git rev-parse --short HEAD)"
      - BUILD_BRANCH="$(git rev-parse --abbrev-ref HEAD)"
      - APP_V="$(cat version)"
      - BUILD_DATE="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
      - BUILD_USER="${WOODPECKER_MACHINE:-woodpecker}"
      - printf "GIT_REV=%s\nBUILD_BRANCH=%s\nAPP_V=%s\nBUILD_DATE=%s\nBUILD_USER=%s\n" \
          "$GIT_REV" "$BUILD_BRANCH" "$APP_V" "$BUILD_DATE" "$BUILD_USER" | tee .env.version

  - name: proto
    image: golang:alpine
    depends_on: [ version ]
    commands:
      - set -eu
      - apk add --no-cache bash git build-base protoc protobuf-dev
      - go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
      - go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
      - export PATH="$(go env GOPATH)/bin:$PATH"
      - bash ci/scripts/proto/generate.sh

  - name: secrets
    image: alpine:latest
    depends_on: [ version ]
    environment:
      VAULT_ADDR: { from_secret: VAULT_ADDR }
      VAULT_ROLE_ID:   { from_secret: VAULT_APP_ROLE }
      VAULT_SECRET_ID: { from_secret: VAULT_SECRET_ID }
    commands:
      - set -euo pipefail
      - apk add --no-cache bash coreutils openssh-keygen curl sed python3
      - mkdir -p secrets
      - ./ci/vlt kv_to_file kv ops/deploy/ssh_key private_b64 secrets/SSH_KEY.b64 600
      - base64 -d secrets/SSH_KEY.b64 > secrets/SSH_KEY
      - chmod 600 secrets/SSH_KEY
      - ssh-keygen -y -f secrets/SSH_KEY >/dev/null
      - ./ci/vlt kv_get kv registry user > secrets/REGISTRY_USER
      - ./ci/vlt kv_get kv registry password > secrets/REGISTRY_PASSWORD

  - name: build-image
    image: gcr.io/kaniko-project/executor:debug
    depends_on: [ proto, secrets ]
    commands:
      - sh ci/scripts/ledger/build-image.sh

  - name: deploy
    image: alpine:latest
    depends_on: [ secrets, build-image ]
    environment:
      VAULT_ADDR: { from_secret: VAULT_ADDR }
      VAULT_ROLE_ID:   { from_secret: VAULT_APP_ROLE }
      VAULT_SECRET_ID: { from_secret: VAULT_SECRET_ID }
    commands:
      - set -euo pipefail
      - apk add --no-cache bash openssh-client rsync coreutils curl sed python3
      - mkdir -p /root/.ssh
      - install -m 600 secrets/SSH_KEY /root/.ssh/id_rsa
      - sh ci/scripts/ledger/deploy.sh
