name: Pull Request

on:
  pull_request_target:
    types:
      - opened
      - reopened
      - synchronize

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v3
        with:
          submodules: recursive
          fetch-depth: 0
          ref: ${{github.event.pull_request.head.ref}}
          repository: ${{github.event.pull_request.head.repo.full_name}}

      - name: Start deployment
        uses: bobheadxi/deployments@v0.6.0
        id: deployment
        with:
          step: start
          token: ${{ github.token }}
          env: pr-${{ github.event.number }}
          ref: ${{ github.head_ref }}
          no_override: false

      - name: Setup Hugo
        uses: peaceiris/actions-hugo@v2
        with:
          hugo-version: latest
          extended: true

      - name: Build
        run: hugo --printI18nWarnings --printPathWarnings --baseURL "https://demo.bbaovanc.com/pull_request/${{ github.event.number }}"

      - name: Compress
        run: |
          time sudo ./compress.sh

      - name: Setup SSH
        uses: kielabokkie/ssh-key-and-known-hosts-action@v1
        with:
          ssh-private-key: ${{ secrets.DEPLOY_SSH_KEY }}
          ssh-host: srv.bbaovanc.com
          ssh-port: 2222

      - name: Upload
        uses: up9cloud/action-rsync@v1
        env:
          HOST: srv.bbaovanc.com
          USER: droneci
          PORT: 2222
          SOURCE: public/
          MODE: push
          VERBOSE: true
          KEY: ${{secrets.DEPLOY_SSH_KEY}}
          TARGET: /var/www/demo.bbaovanc.com/pull_request/${{ github.event.number }}/
          ARGS: -avPzc --delete-delay --exclude=/.git/ --exclude=/.github/

      - name: Finish deployment
        uses: bobheadxi/deployments@v0.6.0
        if: always()
        with:
          step: finish
          token: ${{ github.token }}
          status: ${{ job.status }}
          deployment_id: ${{ steps.deployment.outputs.deployment_id }}
          env_url: "https://demo.bbaovanc.com/pull_request/${{ github.event.number }}/"
          no_override: true
          auto_inactive: false

      - name: Find PR comment
        uses: peter-evans/find-comment@v1
        id: fc
        with:
          issue-number: ${{ github.event.number }}
          comment-author: 'github-actions[bot]'
          body-includes: "preview of this pull request"

      - name: Comment on PR
        uses: peter-evans/create-or-update-comment@v1
        with:
          comment-id: ${{ steps.fc.outputs.comment-id }}
          issue-number: ${{ github.event.number }}
          body: |
            A preview of this pull request is ready!
            See it at https://demo.bbaovanc.com/pull_request/${{ github.event.number }}/
            View the deploy log at https://github.com/BBaoVanC/bbaovanc.com/actions/runs/${{ github.run_id}}
          edit-mode: replace
