How This Website Works

I postponed many years setting this website as I didn’t know what to put up in a personal site, until recently I decided to write up about the projects that I make. Even if I don’t finish them or they are something not flashy enough to show off or share in my Github I can have some record of having done it.

I have been before in the position of remembering that I already did something like what I want to do now but I do not remember the how, so better to write it up and have it in a publicly accessible place.

Static Site

I always found funny that web sites generates the same content again and again for every request they get, I always thought that the way to go is to generate the page once everytime it changes, cache it to disk and then just let a simple HTTP server deliver those pages, that’s why I chose to use a static site generator to build this site, just regenerate whatever changed everytime I send some new content to the public branch of the site repository. This was quite easily done using Git hooks.

I set it up so when the repository receives a new push it runs a script that basically checks if the update is for the public branch, creates a temporary checkout of the repository on /tmp, pulls the theme as Git submodule and generates the site. I took code from somewhere on the Web so it makes a backup before starting and recovers the last version of the site if it fails.

This is the code that I run in the post-receive hook in the bare repository on my server:

#!/bin/bash

DOMAIN=rdleon.me
GIT_REPO=$HOME/repos/rdleon-web.git
WORKING_DIRECTORY=/tmp/$DOMAIN
PUBLIC_WWW=/var/www/$DOMAIN
BACKUP_WWW=/tmp/$DOMAIN-backup

set -e

while read oldrev newrev refname
do
    branch=$(git rev-parse --symbolic --abbrev-ref $refname)
    if [ "public" = "$branch" ]; then
        rm -rf $WORKING_DIRECTORY

        if [[ -d $PUBLIC_WWW ]]; then
            rsync -aqz $PUBLIC_WWW/ $BACKUP_WWW
        fi

        trap "echo 'A problem occurred.  Reverting to backup.'; rsync -aqz --del $BACKUP_WWW/ $PUBLIC_WWW; rm -rf $WORKING_DIRECTORY" EXIT

        git clone $GIT_REPO $WORKING_DIRECTORY

        # Add any git submodules here so that they are included during the build.
        pushd $WORKING_DIRECTORY
        # This is needed to fix an issue with operating on a git repository from a git repository
        GIT_DIR=.git/
        git submodule update --init --recursive --remote
        popd

        if [[ -d $PUBLIC_WWW ]]; then
            rm -rf $PUBLIC_WWW/*
        else
            mkdir $PUBLIC_WWW
        fi

        hugo -s $WORKING_DIRECTORY -d $PUBLIC_WWW/ -b "https://${DOMAIN}"

        rm -rf $WORKING_DIRECTORY
        trap - EXIT
    fi
done

2025-01-02