name: translate update

on:
  push:
    branches:
      - master
    paths:
      - src/main/resources/assets/skyblocker/lang/en_us.json

jobs:
  webhook:
    if: github.repository_owner == 'SkyblockerMod'
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Set up Go
        uses: actions/setup-go@v5
        with:
          go-version: '1.20'

      - uses: actions/cache@v4
        with:
          path: ~/go/pkg/mod
          key: ${{ runner.os }}-go-pkg-mod-${{ hashFiles('go.sum') }}

      - name: Install jd
        run: go install github.com/josephburnett/jd@latest

      - name: Translate notification
        shell: bash
        run: |
          OUTPUT=$(go run github.com/josephburnett/jd@latest <(git show HEAD^:src/main/resources/assets/skyblocker/lang/en_us.json) <(git show HEAD:src/main/resources/assets/skyblocker/lang/en_us.json) || true)
          
          MAX_LENGTH=4070
          
          if [ "${#OUTPUT}" -gt "$MAX_LENGTH" ]; then
          
              OUTPUT="${OUTPUT:0:$MAX_LENGTH}"
          
              LAST_INDEX=-1
              for (( i=${#OUTPUT}-1; i>=0; i-- )); do
                  if [[ "${OUTPUT:$i:1}" =~ [-+@] ]]; then
                      LAST_INDEX=$i
                      break
                  fi
              done
              
              if [[ $LAST_INDEX -ne -1 && "${OUTPUT:$LAST_INDEX:1}" =~ [-+] ]]; then

                  for (( i=LAST_INDEX-1; i>=0; i-- )); do
                      if [[ "${OUTPUT:$i:1}" == "@" ]]; then
                          OUTPUT="${OUTPUT:0:i}"
                          break
                      fi
                  done
              else
              
                  OUTPUT="${OUTPUT:0:LAST_INDEX}"
              fi
          fi
          
          OUTPUT+="..."
          
          OUTPUT="\`\`\`diff
          $OUTPUT
          \`\`\`"
          
          JSON_PAYLOAD='{
          "content": "<@&1134566053138145330>",
          "embeds": [
            {
              "title": "Something Changed (Click me)",
              "description": '"$(echo "$OUTPUT" | jq -Rsa .)"',
              "url": "https://translate.hysky.de/projects/Skyblocker/skyblocker",
              "color": 5808639,
              "image": {
                "url": "https://translate.hysky.de/widgets/Skyblocker/-/skyblocker/88x31-grey.png?uuid='$(uuidgen)'"
              }
            }
          ],
          "attachments": []
          }'
          
          if echo "$JSON_PAYLOAD" | jq . &>/dev/null; then
            curl -H "Content-Type: application/json" --data-binary "$JSON_PAYLOAD" "${{ secrets.DISCORD_TRANSLATE_WEBHOOK }}"
          else
            echo "Error:"
            echo "$JSON_PAYLOAD"
          fi