name: develop Workflow

on:
  pull_request:
    branches:
      - main

jobs:
  build-image:
    name: Build Docker image
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
        name: Check out code

      - name: Check for appmanage changes
        id: check_changes
        run: |
          PR_NUMBER=$(echo "${{ github.event.pull_request.url }}" | awk -F/ '{print $NF}')
          PR_FILES=$(curl -s -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \
            "https://api.github.com/repos/${{ github.repository }}/pulls/${PR_NUMBER}/files")

          if echo "${PR_FILES}" | jq -e '.[] | select(.filename | contains("appmanage/"))' >/dev/null; then
            echo "appmanage directory changed"
            echo "::set-output name=appmanage_changed::true"
          else
            echo "appmanage no change"
            echo "::set-output name=appmanage_changed::false"
          fi

      - name: Get version
        if: ${{ steps.check_changes.outputs.appmanage_changed == 'true' }}
        run: |
          version=$(grep -Po '(?<=LABEL version=").*?(?=")' appmanage/Dockerfile)
          echo $version
          echo "::set-output name=version::$version"
          echo "VERSION=$version" >> $GITHUB_ENV
          echo ${{ secrets.DOCKER_USERNAME }}
          echo ${{ secrets.DOCKER_PASSWORD }}

      - uses: mr-smithers-excellent/docker-build-push@v5
        name: Build & push Docker image
        if: ${{ steps.check_changes.outputs.appmanage_changed == 'true' }}
        with:
          image: websoft9dev/appmanage
          tags: ${{ env.VERSION }}
          registry: docker.io
          dockerfile: appmanage/Dockerfile
          directory: appmanage
          username: websoft9admin
          password: Qiaofeng@1227

  ci-test:
    needs: build-image
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v2

      - name: Get source branch commit
        id: source_commit
        run: echo "::set-output name=commit::${{ github.event.pull_request.head.sha }}"

      - name: Fetch source branch
        run: git fetch origin ${{ steps.source_commit.outputs.commit }}:${{ steps.source_commit.outputs.commit }}

      - name: Checkout source branch
        run: git checkout ${{ steps.source_commit.outputs.commit }}

      - name: Test
        run: |
          cat README.md && cat version.json
