name: Gitea Action Maven build

on:
  push:
    branches: ['master']

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout the repo
        uses: actions/checkout@v4

      - name: Set up Maven
        uses: stCarolas/setup-maven@v5
        with:
          maven-version: 3.9.9

      - name: Set up JDK 21
        uses: actions/setup-java@v4
        with:
          java-version: 21
          distribution: 'oracle'
          cache: 'maven'

      - name: Build, Test and Package with Maven
        run: mvn -B verify --file pom.xml -e

      - name: Upload artifact
        uses: actions/upload-artifact@v3
        with:
          name: searchengine-artifact
          path: |
            target/*.jar
            Dockerfile
            docker-compose.yml

      - name: Create Maven settings.xml
        run: |
          cat <<EOF > ~/.m2/settings.xml
          <settings>
            <servers>
              <server>
                <id>gitea</id>
                <username>${{ vars.OWNER }}</username>
                <password>${{ secrets.ACCESS_TOKEN }}</password>
              </server>
            </servers>
          </settings>
          EOF

      - name: Replace {owner} in pom.xml
        run: sed -i "s/{owner}/${{ vars.OWNER }}/g" pom.xml

      - name: Deploy to Gitea Packages
        run: mvn deploy

  deploy:
    runs-on: ubuntu-latest
    needs: build
    steps:
      - name: Download artifact
        uses: actions/download-artifact@v3
        with:
          name: searchengine-artifact
          path: artifact

      - name: Install SSH Key
        uses: shimataro/ssh-key-action@v2
        with:
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          known_hosts: ${{ secrets.KNOWN_HOSTS }}
      - name: Create Directory on Local Server
        run: ssh -T ${{ vars.DEPLOY_USER }}@${{ vars.DEPLOY_HOST }} mkdir -p ${{ vars.DEPLOY_PATH }}

      - name: Deploy to Local Server
        run: scp -r artifact/* ${{ vars.DEPLOY_USER }}@${{ vars.DEPLOY_HOST }}:${{ vars.DEPLOY_PATH }}

      - name: Create .env file on Local Server
        run: |
          ssh -T ${{ vars.DEPLOY_USER }}@${{ vars.DEPLOY_HOST }} << EOF
          echo "DB_USER=${{ secrets.DB_USER }}" > ${{ vars.DEPLOY_PATH }}/.env
          echo "DB_PASSWORD=${{ secrets.DB_PASSWORD }}" >> ${{ vars.DEPLOY_PATH }}/.env
          echo "DB_URL=${{ vars.DB_URL }}" >> ${{ vars.DEPLOY_PATH }}/.env
          EOF

      - name: Build and Run Docker Image with Docker Compose
        run: |
          ssh -T ${{ vars.DEPLOY_USER }}@${{ vars.DEPLOY_HOST }} << EOF
          cd ${{ vars.DEPLOY_PATH }}
          docker compose down
          docker compose up -d --build
          EOF