#!/usr/bin/env bash
set -euo pipefail

REPO="${PARTS_REPO:-/root/Parts.git}"
LIVE="${PARTS_LIVE:-/srv/www/htdocs/Parts}"
BRANCH="${PARTS_BRANCH:-release}"
DEPLOY_SCRIPT="$LIVE/scripts/deploy/release-post-checkout"

while read -r oldrev newrev ref; do
    if [ "$ref" = "refs/heads/$BRANCH" ]; then
        echo "Deploying $BRANCH to live..."

        mkdir -p "$LIVE"
        git --git-dir="$REPO" --work-tree="$LIVE" checkout -f "$BRANCH"

        if [ ! -x "$DEPLOY_SCRIPT" ]; then
            echo "Deploy script is missing or not executable: $DEPLOY_SCRIPT" >&2
            exit 1
        fi

        PARTS_REPO="$REPO" \
            PARTS_LIVE="$LIVE" \
            PARTS_BRANCH="$BRANCH" \
            PARTS_OLDREV="$oldrev" \
            PARTS_NEWREV="$newrev" \
            PARTS_REF="$ref" \
            "$DEPLOY_SCRIPT"

        echo "Deploy finished."
    fi
done
