name: Java Application Build and Deploy
run-name: ${{ gitea.actor }} is testing out Gitea Actions 🚀
on:
  push:
    branches:
      - main  # Trigger on push to main branch

jobs:
  build-and-deploy:
    runs-on: prod # Use the label matching your Gitea runner
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up JDK 17
        uses: actions/setup-java@v4
        with:
          java-version: '17'
          distribution: 'temurin'  # or choose your preferred distribution
          cache: 'maven'

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

      - name: compile with Maven
        run: mvn compile -file pom.xml

      - name: SonarQube Scan
        uses: SonarSource/sonarqube-scan-action@v4
        env:
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
          SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }

      # Trivy Scan
      - name: Trivy Scan
        run: docker run --rm -v /var/run/docker.sock:/var/run/docker.sock aquasec/trivy:latest image actions-app:${{ github.sha}}
        
      - name: Build with Maven
        run: mvn -B package --file pom.xml

      - name: Log in to Nexus Repository
        uses: docker/login-action@v2
        with:
          registry: nexus.example.com:16002
          username: ${{ secrets.NEXUS_USERNAME }}
          password: ${{ secrets.NEXUS_PASSWORD }}   


      - name: Build and push Docker image
        uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          tags: nexus.example.com:16002/myproject/app:${{ github.sha }}  

      - name: Build Docker image 
        run: |
          # Assuming Docker is installed and configured on runner or server
          # Build docker image
          docker build -t my-java-app:latest .

   

          # Stop previous container if running
          docker stop my-java-app || true
          docker rm my-java-app || true
          # Run new container
          docker run -d --name my-java-app -p 8080:8080 my-java-app:latest
