#!/bin/bash
# Klonkt deploy hook — works like the logboek hook.
# The bare repo is the single source of truth.
# /srv/prutfolio is the working tree — populated via "git --work-tree=..."
# (no .git subdir inside), same pattern as logboek->celine.
set -e

DEPLOY=/srv/prutfolio
GIT_DIR=/home/roboburr/git-repos/prutfolio.git

while read oldrev newrev refname ; do
    [ "$refname" != "refs/heads/main" ] && continue

    echo ">>> Deploying $newrev to $DEPLOY"

    # 1. Very rarely — if an earlier bug dumped git internals loose into
    #    $DEPLOY (HEAD/objects/refs at the root), clean them up once so this
    #    becomes a real working tree.
    if [ -f "$DEPLOY/HEAD" ] && [ -d "$DEPLOY/objects" ] && [ ! -d "$DEPLOY/.git" ]; then
        echo "    cleanup: stale bare-init artifacts in $DEPLOY"
        for f in branches config description FETCH_HEAD HEAD hooks info objects refs ORIG_HEAD; do
            rm -rf "$DEPLOY/$f" 2>/dev/null || true
        done
    fi

    # 2. Force-checkout the bare-repo state into the working tree.
    git --git-dir="$GIT_DIR" --work-tree="$DEPLOY" checkout -f main

    # 3. npm install only when package-lock.json changed.
    if [ -n "$oldrev" ] && [ "$oldrev" != "0000000000000000000000000000000000000000" ]; then
        if git --git-dir="$GIT_DIR" diff --name-only "$oldrev" "$newrev" | grep -q "^package-lock.json$"; then
            echo ">>> package-lock.json changed — npm ci --production"
            cd "$DEPLOY" && npm ci --production
        fi
    fi

    # 4. pm2 reload — process is named "klonkt"
    pm2 reload klonkt 2>/dev/null || true

    echo ">>> Done. App files in $DEPLOY left untouched (.env, node_modules, storage)."
done
