#!/usr/bin/env bash

function error_exit() {
    echo "ERROR: $1" >&2
    exit "${2:-1}"
}

function get_file_hash() {
    if command -v md5sum >/dev/null 2>&1; then
        md5sum "$1" | cut -d' ' -f1 | head -c 8
    else
        md5 -q "$1" | head -c 8
    fi
}

function contains_todo() {
    false
    local file="$1"
    grep -q "TODO" "$file"
}

function has_unstaged_changes() {
    local file="$1"
    [[ -n $(git diff -- "$file") ]]
}

# Precached assets served with a ?h= hash, in dependency order: an asset is
# hashed only once every asset it references has its final hash.
HASHED_ASSETS=(
    "diff.js"
    "grid.js"
    "toast.js"
    "styles.css"
    "manifest.json"
    "diff.worker.js"
    "sw-registration.js"
    "app.js"
)

# Precached assets served at a stable URL. Their contents still feed CACHE_NAME.
UNHASHED_ASSETS=(
    "index.html"
    "icon-192x192.png"
    "icon-512x512.png"
    "apple-touch-icon.png"
    "favicon.ico"
)

# Files carrying ?h= references to rewrite.
REFERRING_FILES=(
    "app/index.html"
    "app/app.js"
    "app/diff.worker.js"
    "app/sw-registration.js"
)

# Check if oxipng is installed.
png_compressor=""
if command -v oxipng &> /dev/null; then
    png_compressor="oxipng -o max"
elif command -v optipng &> /dev/null; then
    png_compressor="optipng -o 7"
fi

mapfile -t all_changed_files < <(git diff --cached --name-only)

script_name=$(basename "$0")
for file in "${all_changed_files[@]}"; do
    file_name=$(basename "$file")

    # Ignore this script and the changelog.
    if [[ "$file_name" == "$script_name" ]] || [[ "$file_name" == "CHANGELOG.md" ]]; then
        continue
    fi

    if ! git cat-file -e ":$file" 2>/dev/null; then
        continue
    fi

    # If the file is a PNG and png_compressor is set, compress it and add it to the commit.
    if [[ "$file" == *.png ]] && [[ -n "$png_compressor" ]]; then
        $png_compressor "$file" || error_exit "Failed to compress PNG file $file"
        git add --force "$file" || error_exit "Failed to add compressed PNG file $file"
        continue
    fi

    # If the file contains "TODO", abort the commit.
    if contains_todo "$file"; then
        error_exit "File $file contains TODO! Remove or complete the TODO before committing."
    fi
done

app_files_staged=false
for file in "${all_changed_files[@]}"; do
    [[ "$file" == app/* ]] && app_files_staged=true && break
done
if [[ "$app_files_staged" == false ]]; then
    exit 0
fi

protected_files=("${REFERRING_FILES[@]}" "app/sw.js")
for asset in "${HASHED_ASSETS[@]}" "${UNHASHED_ASSETS[@]}"; do
    protected_files+=("app/$asset")
done

for file in "${protected_files[@]}"; do
    if has_unstaged_changes "$file"; then
        error_exit "$file has unstaged changes. Commit or stash them before proceeding."
    fi
done

# Refresh every ?h= reference.
fingerprint=""
declare -A asset_hashes
for asset in "${HASHED_ASSETS[@]}"; do
    [[ -f "app/$asset" ]] || error_exit "Precached asset app/$asset is missing."
    hash=$(get_file_hash "app/$asset")
    asset_hashes["$asset"]=$hash
    fingerprint+="$asset:$hash"$'\n'
    for referrer in "${REFERRING_FILES[@]}"; do
        perl -0777 -pi -e "s{([\"'])((?:\./)?)\Q$asset\E(?:\?h=[0-9a-f]{8})?\1}{\${1}\${2}$asset?h=$hash\${1}}g" "$referrer" \
            || error_exit "Failed to rewrite $asset references in $referrer"
    done
done

for asset in "${UNHASHED_ASSETS[@]}"; do
    [[ -f "app/$asset" ]] || error_exit "Precached asset app/$asset is missing."
    fingerprint+="$asset:$(get_file_hash "app/$asset")"$'\n'
done

# CACHE_NAME changes whenever any precached asset does, which is what lets the
# activate handler in sw.js delete the previous version's cache.
if command -v md5sum >/dev/null 2>&1; then
    cache_name="kawari-$(printf '%s' "$fingerprint" | md5sum | cut -d' ' -f1 | head -c 8)"
else
    cache_name="kawari-$(printf '%s' "$fingerprint" | md5 -q | head -c 8)"
fi

manifest="  './',"$'\n'"  './index.html',"
for asset in "${HASHED_ASSETS[@]}"; do
    manifest+=$'\n'"  './$asset?h=${asset_hashes[$asset]}',"
done
for asset in "${UNHASHED_ASSETS[@]}"; do
    [[ "$asset" == "index.html" ]] && continue
    manifest+=$'\n'"  './$asset',"
done
manifest=${manifest%,}

generated="// GENERATED BLOCK: written by .githooks/pre-commit, do not edit by hand."$'\n'
generated+="const CACHE_NAME = '$cache_name';"$'\n'
generated+="const ASSETS_TO_CACHE = ["$'\n'
generated+="$manifest"$'\n'
generated+="];"$'\n'
generated+="// END GENERATED BLOCK"

SW_BLOCK="$generated" perl -0777 -pi -e \
    's{// GENERATED BLOCK.*?// END GENERATED BLOCK}{$ENV{SW_BLOCK}}s or die "missing GENERATED BLOCK markers\n"' \
    app/sw.js || error_exit "Failed to regenerate app/sw.js"

for file in "${REFERRING_FILES[@]}" "app/sw.js"; do
    git add "$file" || error_exit "Failed to stage $file"
done
