kind: pipeline
type: docker
name: build-and-push

clone:
  depth: 1

steps:
  - name: build golang app
    image: golang:1.24
    environment:
      GOOS: linux
      GOARCH: amd64
      CGO_ENABLED: 0
    commands:
      - |
        set -e
        SHORT_SHA=$(echo "$DRONE_COMMIT_SHA" | cut -c1-8)
        IMG_TAG="${DRONE_BUILD_NUMBER}-${DRONE_BRANCH}"
        echo -n "$IMG_TAG,$SHORT_SHA" > .tags
        echo "Image tags -> $IMG_TAG , $SHORT_SHA"
      - mkdir -p ./artifacts/go/bin ./artifacts/go/config
      - go env
      - CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -v -o ./artifacts/go/bin/web ./cmd/web/main.go
      - CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -v -o ./artifacts/go/bin/scraper ./cmd/scraper/main.go
      - rm -f cmd/worker/workers/scraper.go cmd/worker/workers/scraper_consumer.go cmd/worker/workers/queue_producer.go
      - CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -v -o ./artifacts/go/bin/worker ./cmd/worker/main.go
      - cp -r ./cmd/web/docs ./artifacts/go/bin/docs
      - cp -r ./cmd/web/assets ./artifacts/go/bin/assets
      - ls -ltrh ./artifacts/go/bin/

  - name: push web
    image: plugins/docker
    settings:
      registry: git.opplens.se
      repo: git.opplens.se/mazyar/web
      username:
        from_secret: registry_username
      password:
        from_secret: registry_password
      dockerfile: ./cmd/web/Dockerfile

  - name: push scraper
    image: plugins/docker
    settings:
      registry: git.opplens.se
      repo: git.opplens.se/mazyar/scraper
      username:
        from_secret: registry_username
      password:
        from_secret: registry_password
      dockerfile: ./cmd/scraper/Dockerfile

  - name: push worker
    image: plugins/docker
    settings:
      registry: git.opplens.se
      repo: git.opplens.se/mazyar/worker
      username:
        from_secret: registry_username
      password:
        from_secret: registry_password
      dockerfile: ./cmd/worker/Dockerfile

  - name: deploy-uat
    image: appleboy/drone-ssh
    settings:
      host: 10.0.0.3
      username: mazyar
      port: 22
      key:
        from_secret: ssh_deploy_key
      envs:
        - DRONE_BUILD_NUMBER
        - DRONE_BRANCH
      script:
        - set -e
        - cd /data/tm-uat
        - NEW_TAG="${DRONE_BUILD_NUMBER}-${DRONE_BRANCH}"
        - echo "Deploying tag $NEW_TAG"
        - sed -i "s/^WEB_IMG_TAG=.*/WEB_IMG_TAG=$NEW_TAG/"         .env
        - sed -i "s/^SCRAPER_IMG_TAG=.*/SCRAPER_IMG_TAG=$NEW_TAG/" .env
        - sed -i "s/^WORKER_IMG_TAG=.*/WORKER_IMG_TAG=$NEW_TAG/"   .env
        - docker compose pull web scraper worker
        - docker compose up -d web scraper worker
        - docker image prune -f
    when:
      branch:
        - dev

trigger:
  branch:
    - main
    - uat
    - dev
  event:
    - push
