name: Build SimplySyncedLLC.com

on:
  push:
    branches:
    - master

jobs:
  build-project:
    name: Build and Deploy
    runs-on: host
    steps:
    - name: Check out repository code
      uses: actions/checkout@v4

    - uses: actions/github-script@v7
      id: set-result
      with:
        script: |
          var fs = require("fs")
          var content = fs.readFileSync("package.json", { encoding: 'utf8', flag: 'r' })
          var pkg = JSON.parse(content)
          return pkg.version
        result-encoding: string

    - name: Get result
      run: echo "gitea.simplysyncedllc.com/dex/ss_website:${{steps.set-result.outputs.result}}"

    - name: Install QEMU
      run: apt-get update && apt-get install -y qemu-user-static

    - name: Set up Docker Buildx
      uses: docker/setup-buildx-action@v3

    - name: Setup Node
      uses: actions/setup-node@v4
      with:
        node-version: '18.20.0'

    - name: Create a new release and publish package.
      id: release
      run: |
        CURR_VER="$(cat package.json | jq -r .name)_v$(cat package.json | jq -r .version)"
        CURR_NAME="$(cat package.json | jq -r .name) v$(cat package.json | jq -r .version)"

        echo "Checking https://gitea.simplysyncedllc.com/api/v1/repos/${{ gitea.repository }}/releases for name ${CURR_NAME}"

        if curl -s -X GET -H "Authorization: token ${{ secrets.ACTION_TOKEN }}" https://gitea.simplysyncedllc.com/api/v1/repos/${{ gitea.repository }}/releases | grep -o "\"name\"\:\"${CURR_NAME}\"" > /dev/null; then
          echo "Skipping ${{ gitea.job }} since $CURR_NAME already exists";
          exit 0
        fi

        echo "New release ${CURR_VER} found, running npm install..."

        npm install && npm run build

        echo "Creating ${CURR_VER} release on gitea"
        RELEASE_RESULT=$(curl \
          -X POST \
          -H "Authorization: token ${{ secrets.ACTION_TOKEN }}" \
          -H "Content-Type: application/json" \
          https://gitea.simplysyncedllc.com/api/v1/repos/${{ gitea.repository }}/releases \
          -d "{\"tag_name\":\"${CURR_VER}\",\"name\":\"${CURR_NAME}\",\"body\":\"Automatic release from gitea :\n\n${{ gitea.event.head_commit.message }}\"}")


        RELEASE_ID=$(echo $RELEASE_RESULT | jq -r .id)
        echo "Adding ${CURR_VER}_build-sc.7z to release ${RELEASE_ID}"

        curl \
          -X POST \
          -H "Authorization: token ${{ secrets.ACTION_TOKEN }}" \
          -H "Content-Type: application/json" \
          https://gitea.simplysyncedllc.com/api/v1/repos/${{ gitea.repository }}/releases/$RELEASE_ID/assets

    - name: Build and push
      uses: docker/build-push-action@v5
      with:
        context: .
        file: ./Dockerfile
        platforms: |
          linux/arm64
        push: true
        tags: |
          gitea.simplysyncedllc.com/dex/ss_website:latest
          gitea.simplysyncedllc.com/dex/ss_website:${{steps.set-result.outputs.result}}
