name: Update odoo 18
run-name: ${{ gitea.actor }} is testing out Gitea Actions
on:
  push:
    branches:
      - dev
    # paths:
    #   - '**/docker-compose.yml'
    #   - '**/.env'

jobs:
  update:
    runs-on: ubuntu-22.04
    steps:
      - name: Setup correct time in build container
        run: ln -sf /usr/share/zoneinfo/Asia/Tbilisi /etc/localtime
      
      - name: Install sshpass
        run: apt update && apt install -y sshpass
      
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          github-server-url: http://10.0.0.8:3000
          repository: gitea/bross_hms
          token: ${{ secrets.PAT }}
          path: .
          fetch-depth: 0

      # - name: Testing
      #   run: |
      #     modules_to_update=$(git diff --name-only ${{ gitea.event.before }}..${{ gitea.event.after }} | awk -F/ '{print $1}')
      #     echo $modules_to_update
          
      #     export SSHPASS=${{ secrets.SERVER_SSH_PASSWORD }}
      #     export STACK_PATH="/home/sysop/odoo18/customaddons/bross_hms"

      #     sshpass -e ssh -p ${{ secrets.SERVER_SSH_PORT }} -o StrictHostKeyChecking=no \
      #       ${{ secrets.SERVER_SSH_USER }}@${{ secrets.SERVER_SSH_HOST }} "echo $modules_to_update > testing_file"

      - name: Deploy to dev environment
        if: gitea.ref == 'refs/heads/dev'
        run: |
          export SSHPASS=${{ secrets.SERVER_SSH_PASSWORD }}
          export STACK_PATH="/home/sysop/odoo18/customaddons/bross_hms"
          
          git config --global --add safe.directory $STACK_PATH

          ### Get modules list to update 
          modules_to_update=$(git diff --name-only ${{ gitea.event.before }}..${{ gitea.event.after }} | awk -F/ '{print $1}' | uniq | xargs -I {} sh -c 'find {} -type f -name "__manifest__.py" | grep -q "__manifest__.py" && echo {}' 2>/dev/null | sed -z 's/\n/,/g; s/,$/\n/')
          echo $modules_to_update
          
          ### Generate update string
          if [ -z "${modules_to_update}" ]; then
            echo "No module to update"
          else
            echo "Modules to update set"
            args="-d bross_hms_dev -u ${modules_to_update}"
            sshpass -e ssh -p ${{ secrets.SERVER_SSH_PORT }} -o StrictHostKeyChecking=no \
              ${{ secrets.SERVER_SSH_USER }}@${{ secrets.SERVER_SSH_HOST }} \
              "cd $STACK_PATH && git pull && docker compose -f docker-compose-dev.yml down && export ARGS='${args}' && docker compose -f docker-compose-dev.yml up -d"
          fi