name: Deploy service tg-bot
run-name: ${{ github.actor }} deployed to build branch
on:
  push:
    branches:
      - main
    paths:
      - 'services/tg-bot/**'
      - 'packages/couchdb-changes-stream/**'
      - '.gitea/workflows/deploy-service-tg-bot.yaml'
      - 'docker-compose.yml'
      - 'package.json'
      - 'pnpm-lock.yaml'

jobs:
  service tg-bot:
    runs-on: ubuntu-latest

    env:
      COUCHDB_USER: ${{ secrets.COUCHDB_USER }}
      COUCHDB_PASSWORD: ${{ secrets.COUCHDB_PASSWORD }}
      BOT_TOKEN: ${{ secrets.BOT_TOKEN }}
      READ_BASE_URL: ${{ vars.READ_BASE_URL }}
      APP_BASE_URL: ${{ vars.APP_BASE_URL }}
      HEARTBEAT_INTERVAL: ${{ vars.HEARTBEAT_INTERVAL }}
      BOT_USE_CHANGES_DB_UPDATES: ${{ vars.BOT_USE_CHANGES_DB_UPDATES }}

    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'

#      - name: install system packages
#        run: |
#          apt-get update && apt-get install -y libcairo2-dev libjpeg-dev libpango1.0-dev libgif-dev build-essential g++ && apt-get clean && rm -rf /var/lib/apt/lists/*

      - name: install dependencies
        run: |
          corepack enable pnpm && corepack use pnpm@9.15.0
          pnpm install --filter ./services/tg-bot

      - name: build service
        run: |
          pnpm run --filter ./services/tg-bot build
          pnpm --filter ./services/tg-bot deploy --prod build/service-tg-bot

      - name: build docker image
        run: TG_BOT_TAG=commit-${{env.GITHUB_SHA}} docker compose -p hereconnect build tg-bot

      - name: start container
        run: TG_BOT_DEBUG='grammy*' TG_BOT_TAG=commit-${{env.GITHUB_SHA}} docker compose -p hereconnect up -d --pull never --wait tg-bot

      - name: rename to latest
        run: docker tag hereconnect/service-tg-bot:commit-${{env.GITHUB_SHA}} hereconnect/service-tg-bot:latest

      - name: rollback on failure
        if: failure()
        env:
          COUCHDB_TAG: latest
        run: |
          TG_BOT_TAG=commit-${{env.GITHUB_SHA}} docker compose -p hereconnect logs tg-bot
          docker compose -p hereconnect up -d --pull never --wait tg-bot

      - name: cleanup docker image
        if: always()
        run: docker rmi hereconnect/service-tg-bot:commit-${{env.GITHUB_SHA}}
