name: Continuous Delivery - ts-config

on:
  push:
    branches:
      - main
    paths:
      - packages/ts-config/**
      - .all-contributorsrc
      - LICENSE.md
      - package.json
      - .github/workflows/cd-ts-config.yml
jobs:
  pre_ci:
    name: Prepare CI environment
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Project
        uses: actions/checkout@v2
        with:
          fetch-depth: 2
      - name: '[Push] Get commit message'
        if: github.event_name == 'push'
        id: push_get_commit_message
        run: echo ::set-output name=push_commit_message::$(git log --format=%B -n 1 HEAD)
      - name: '[Pull Request] Get commit message'
        if: github.event_name == 'pull_request'
        id: pr_get_commit_message
        run: echo ::set-output name=pr_commit_message::$(git log --format=%B -n 1 HEAD^2)
      - name: Add problem matchers
        run: |
          echo "::add-matcher::.github/problemMatchers/tsc.json"
          echo "::add-matcher::.github/problemMatchers/eslint-stylish.json"
    outputs:
      commit_message: $( [ -z "${{ steps.pr_get_commit_message.outputs.pr_commit_message }}" ] && echo "${{ steps.push_get_commit_message.outputs.push_commit_message }}" || echo "${{ steps.pr_get_commit_message.outputs.pr_commit_message }}" )

  BuildTSConfig:
    name: Publish TS config
    runs-on: ubuntu-latest
    if: "!contains(needs.pre_ci.outputs.commit_message, '[skip ci]')"
    needs: pre_ci
    steps:
      - name: Checkout Project
        uses: actions/checkout@v2
      - name: Push new code
        if: github.event_name == 'push' && github.ref == 'refs/heads/main'
        run: |
          REPO="https://${GITHUB_ACTOR}:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git"

          echo -e "\n# Move to the tsconfig directory"
          cd packages/ts-config

          echo -e "\n# Checkout the repo in the target branch"
          TARGET_BRANCH="build-tsconfig"
          git clone $REPO out -b $TARGET_BRANCH

          echo -e "\n# Remove any old files in the dist folder"
          rm -rfv out/tsconfig.json

          echo -e "\n# Move the generated code to the newly-checked-out repo, to be committed and pushed"
          rsync -vaI package.json out/
          rsync -vaI ../../.all-contributorsrc out/
          rsync -vaI ../../LICENSE.md out/
          rsync -vaI README.md out/
          rsync -vaI src/tsconfig.json out/

          echo -e "\n# Commit and push"
          cd out
          git add --all .
          git config user.name "${GITHUB_ACTOR}"
          git config user.email "${GITHUB_EMAIL}"
          git commit -m "build: ts-config build for ${GITHUB_SHA}" || true
          git push origin $TARGET_BRANCH
        env:
          GITHUB_TOKEN: ${{ secrets.SKYRA_TOKEN }}
          GITHUB_ACTOR: NM-EEA-Y
          GITHUB_EMAIL: contact@skyra.pw
