name: Deploy Blog

on:
  push:
    branches:
      - master
      - main
  workflow_dispatch:

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout source
        uses: actions/checkout@v4

      - name: Install build dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y curl git rsync openssh-client tar

      - name: Install Hugo Extended
        env:
          HUGO_VERSION: "0.145.0"
        run: |
          curl -fsSL -o hugo.deb \
            "https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_extended_${HUGO_VERSION}_linux-amd64.deb"
          sudo dpkg -i hugo.deb
          hugo version

      - name: Bootstrap LoveIt theme
        run: |
          chmod +x scripts/bootstrap-theme.sh
          ./scripts/bootstrap-theme.sh

      - name: Build site
        run: |
          hugo --gc --minify
          test -f public/index.html

      - name: Configure SSH
        env:
          BLOG_DEPLOY_KEY: ${{ secrets.BLOG_DEPLOY_KEY }}
          BLOG_DEPLOY_KNOWN_HOSTS: ${{ secrets.BLOG_DEPLOY_KNOWN_HOSTS }}
        run: |
          install -d -m 700 ~/.ssh
          printf '%s\n' "$BLOG_DEPLOY_KEY" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519
          if [ -n "${BLOG_DEPLOY_KNOWN_HOSTS}" ]; then
            printf '%s\n' "$BLOG_DEPLOY_KNOWN_HOSTS" > ~/.ssh/known_hosts
            chmod 644 ~/.ssh/known_hosts
          fi

      - name: Deploy to server
        env:
          BLOG_DEPLOY_HOST: ${{ secrets.BLOG_DEPLOY_HOST }}
          BLOG_DEPLOY_PORT: ${{ secrets.BLOG_DEPLOY_PORT }}
          BLOG_DEPLOY_USER: ${{ secrets.BLOG_DEPLOY_USER }}
          BLOG_DEPLOY_PATH: ${{ secrets.BLOG_DEPLOY_PATH }}
        run: |
          test -n "$BLOG_DEPLOY_HOST"
          test -n "$BLOG_DEPLOY_PORT"
          test -n "$BLOG_DEPLOY_USER"
          test -n "$BLOG_DEPLOY_PATH"
          SSH_OPTS="-p $BLOG_DEPLOY_PORT"
          if [ ! -f ~/.ssh/known_hosts ]; then
            SSH_OPTS="$SSH_OPTS -o StrictHostKeyChecking=accept-new"
          fi
          ssh $SSH_OPTS "$BLOG_DEPLOY_USER@$BLOG_DEPLOY_HOST" "mkdir -p '$BLOG_DEPLOY_PATH/public'"
          rsync -az --delete \
            -e "ssh $SSH_OPTS" \
            public/ "$BLOG_DEPLOY_USER@$BLOG_DEPLOY_HOST:$BLOG_DEPLOY_PATH/public/"
