name: Build Quartz Notes

on:
  push:
    branches:
      - main

  schedule:
    - cron: "0 0 * * *"

  workflow_dispatch:

jobs:
  build:
    runs-on: site-build
    env:
      VAULT_HOME: /home/zaine/master-folder/vault-master
      QUARTZ_HOME: /home/zaine/Documents/quartz
      SERVICE_NAME: quartz-notes.service
      SUDO_PASSWORD: ${{ secrets.SUDO_PASSWORD }}

    steps:
      - uses: actions/checkout@v4

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: "22"

      - name: Verify toolchain
        run: |
          node --version
          npm --version
          npx --version

      - name: Update vault content
        run: |
          set -euo pipefail

          git -C "$VAULT_HOME" fetch origin main
          git -C "$VAULT_HOME" checkout main
          git -C "$VAULT_HOME" pull --ff-only origin main

      - name: Build Quartz
        run: |
          set -euo pipefail

          test "$(readlink -f "$QUARTZ_HOME/content")" = "$(readlink -f "$VAULT_HOME")"

          cd "$QUARTZ_HOME"
          npm exec -- quartz build

      - name: Install and restart Quartz service
        run: |
          set -euo pipefail
          echo "$SUDO_PASSWORD" | sudo -S install -m 0644 "$VAULT_HOME/systemd/$SERVICE_NAME" "/etc/systemd/system/$SERVICE_NAME"
          echo "$SUDO_PASSWORD" | sudo -S systemctl daemon-reload
          echo "$SUDO_PASSWORD" | sudo -S systemctl enable "$SERVICE_NAME"
          echo "$SUDO_PASSWORD" | sudo -S systemctl restart "$SERVICE_NAME"
          systemctl is-active --quiet "$SERVICE_NAME"
