name: Deploy Hugo Site

on:
  push:
    branches:
      - main
      - forge-ci

jobs:
  build-and-deploy:
    runs-on: ubuntu-24.04

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          submodules: recursive
          fetch-depth: 0

      - name: Install Hugo - latest version
        run: |
          apt-get update -y
          apt-get install -y wget tar jq # Install necessary components
          ldd --version
          
          # If a Hugo version is provided in the secrets, use this
          # else latest will be used
          if [ -n "${{ secrets.HUGO_VERSION }}" ]; then
            HUGO_VERSION="${{ secrets.HUGO_VERSION }}"
            echo "Using Hugo version from secret: $HUGO_VERSION"
          else
          # Use the GitHub API to get information about the latest release, then use jq to find out the tag name
            HUGO_VERSION=$(wget -qO- https://api.github.com/repos/gohugoio/hugo/releases/latest | jq -r '.tag_name')
            echo "Using latest Hugo version: $HUGO_VERSION"
          fi
          
          # Use ${HUGO_VERSION#v} to strip the v from v1.0.0
          # See "Substring Removal" in https://tldp.org/LDP/abs/html/string-manipulation.html
          wget -O hugo.tar.gz "https://github.com/gohugoio/hugo/releases/download/${HUGO_VERSION}/hugo_extended_${HUGO_VERSION#v}_Linux-64bit.tar.gz"
          tar -xzf hugo.tar.gz hugo
          mv hugo /usr/local/bin/hugo
          chmod +x /usr/local/bin/hugo
          ldd /usr/local/bin/hugo
          hugo version

      - name: Build site
        run: hugo --minify

      - name: Deploy to server via rsync
        env:
          DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }}
          DEPLOY_USER: ${{ secrets.DEPLOY_USER }}
          DEPLOY_PATH: ${{ secrets.DEPLOY_PATH }}
        run: |
          apt-get install -y rsync openssh-client
          mkdir -p ~/.ssh
          echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519
          ssh-keyscan -H "$DEPLOY_HOST" >> ~/.ssh/known_hosts
          rsync -avz --delete public/ "$DEPLOY_USER@$DEPLOY_HOST:$DEPLOY_PATH"
