#!/bin/bash

version="0.2.1"
script_dir=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
tmp_dir="$(mktemp -d --suffix=-web)"
cleanup () { rm -Rfv "$tmp_dir"; }
trap cleanup EXIT

theme_dir="$script_dir/themes/LoveIt"
release_json="$theme_dir/release.json"
latest_theme_release_metadata="$(curl -s https://api.github.com/repos/dillonzq/LoveIt/releases/latest)" || exit 1
latest_theme_tag_name="$(jq -r .tag_name <<<"${latest_theme_release_metadata:?}")" || exit 2
previous_theme_tag_name="$(jq -r .tag_name "$release_json" 2>/dev/null)" || exit 3

if [[ "$latest_theme_tag_name" != "$previous_theme_tag_name" ]]; then
    echo "Updating theme: '$latest_theme_tag_name' != '$previous_theme_tag_name'"
    curl -L "https://github.com/dillonzq/LoveIt/archive/refs/tags/${latest_theme_tag_name:?}.tar.gz" -o "$tmp_dir/theme.tgz" || exit 11
    tar -xvf "$tmp_dir/theme.tgz" -C "$tmp_dir" || exit 12
    [ -d "$theme_dir" ] && { rm -Rv "$theme_dir"* || exit 13; }
    mv "$tmp_dir/LoveIt"* "$theme_dir" || exit 14
    rm -Rv "$theme_dir/exampleSite"
    echo "$latest_theme_release_metadata" >"$release_json"
fi

rm -R resources .hugo_build.lock

docker build "$script_dir" -f Containerfile -t jilits/website:latest -t jilits/website:$version -t git.jilits.se/jilits/website:$version
