#!/bin/sh

# This script detects changes in static files after git pull
# It outputs a list of subprojects that need to be rebuilt

set -e

die() {
    >&2 echo "error: $*"
    exit 1
}

if ! command -v yq >/dev/null 2>&1; then
    die "yq is not installed. Please install yq to parse YAML files."
fi

APP_DIR=
PREV_COMMIT=
CURR_COMMIT=

usage() {
    cat <<EOF
usage: $(basename "$0") [OPTIONS]

Options:
    -a  app directory
    -p  previous commit hash
    -c  current commit hash
    -h  show this help
EOF
    exit 1
}

while [ $# -gt 0 ]; do
    case $1 in
        -a) APP_DIR="$2"; shift ;;
        -p) PREV_COMMIT="$2"; shift ;;
        -c) CURR_COMMIT="$2"; shift ;;
        -h) usage ;;
        *) die "unexpected argument: $1" ;;
    esac
    shift
done

[ -z "$APP_DIR" ] && die "app directory not specified"
[ -z "$CURR_COMMIT" ] && die "current commit hash not specified"

SCRIPT_DIR=$(cd "$(dirname "$(readlink -f "$0")")" && pwd)
PROJECTS=$("$SCRIPT_DIR"/get_projects.sh "$APP_DIR/config.yaml")

# If no previous commit is specified, assume all projects need to be rebuilt
if [ -z "$PREV_COMMIT" ]; then
    echo "$PROJECTS"
    exit 0
fi

cd "$APP_DIR"

# Check if common files have changed
common_changed=$(git diff --name-only "$PREV_COMMIT" "$CURR_COMMIT" -- "$APP_DIR/public/common")
if [ -n "$common_changed" ]; then
    # If common files have changed, all projects need to be rebuilt
    echo "$PROJECTS"
    exit 0
fi

# Check which project-specific files have changed
projects_changed=""
for project in $PROJECTS; do
    project_changed=$(git diff --name-only "$PREV_COMMIT" "$CURR_COMMIT" -- "$APP_DIR/public/$project")
    if [ -n "$project_changed" ]; then
        projects_changed="$projects_changed $project"
    fi
done

# Output the list of projects that need to be rebuilt
echo "$projects_changed"
