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

MAIN_PROJECT="/workspace/wwwroot/zhct_sfd/project"
AI_PROJECT="/workspace/wwwroot/aizhct_sfd/project"
MAIN_CRON="$MAIN_PROJECT/application/cron/shell/prod/sfd/cron.yml"
AI_CRON="$AI_PROJECT/cron/shell/prod/sfd/cron.yml"
SUPERVISOR_SOURCE="$MAIN_PROJECT/application/cron/shell/prod/supervisor/sfd"
SUPERVISOR_TARGET="/etc/supervisor/conf.d"
CRON_BEGIN="# BEGIN SIFANGDA PROJECT CRON"
CRON_END="# END SIFANGDA PROJECT CRON"

if [ "$(id -u)" -ne 0 ]; then
    echo "Run as root after both Sifangda projects are deployed." >&2
    exit 1
fi

for required_path in \
    "$MAIN_PROJECT/think" \
    "$AI_PROJECT/think" \
    "$MAIN_CRON" \
    "$AI_CRON" \
    "$SUPERVISOR_SOURCE"; do
    if [ ! -e "$required_path" ]; then
        echo "Project runtime source is missing: $required_path" >&2
        exit 1
    fi
done

shopt -s nullglob
supervisor_files=("$SUPERVISOR_SOURCE"/*.ini)
if [ "${#supervisor_files[@]}" -eq 0 ]; then
    echo "No Sifangda Supervisor program files found in $SUPERVISOR_SOURCE" >&2
    exit 1
fi

if grep -RInE 'zhct_bzjk|aizhct_bzjk|bziht|10\.10\.12\.|yyangpt|kxunpt' \
    "$MAIN_CRON" "$AI_CRON" "$SUPERVISOR_SOURCE"; then
    echo "Cross-customer residue found in project runtime configuration." >&2
    exit 1
fi

if grep -RIn '/current/' "$MAIN_CRON" "$AI_CRON" "$SUPERVISOR_SOURCE"; then
    echo "Cron and Supervisor must point to the project runtime directory, not current." >&2
    exit 1
fi

if ! grep -qF "$MAIN_PROJECT/" "$MAIN_CRON"; then
    echo "Main Cron does not point to the main project runtime directory." >&2
    exit 1
fi

if ! grep -qF "$AI_PROJECT/" "$AI_CRON"; then
    echo "AI Cron does not point to the AI project runtime directory." >&2
    exit 1
fi

for supervisor_file in "${supervisor_files[@]}"; do
    if ! grep -Eq '^directory=/workspace/wwwroot/(zhct_sfd|aizhct_sfd)/project/?$' "$supervisor_file"; then
        echo "Supervisor directory is not a Sifangda project runtime path: $supervisor_file" >&2
        exit 1
    fi
done

mkdir -p "$SUPERVISOR_TARGET"
install -m 0644 "${supervisor_files[@]}" "$SUPERVISOR_TARGET/"

existing_cron="$(mktemp)"
next_cron="$(mktemp)"
base_cron="$(mktemp)"
cleanup() {
    rm -f "$existing_cron" "$next_cron" "$base_cron"
}
trap cleanup EXIT

crontab -u www -l > "$existing_cron" 2>/dev/null || true
awk -v begin="$CRON_BEGIN" -v end="$CRON_END" '
    $0 == begin { skip = 1; next }
    $0 == end { skip = 0; next }
    !skip { print }
' "$existing_cron" > "$base_cron"

{
    cat "$base_cron"
    printf '%s\n' "$CRON_BEGIN"
    sed -e '/^[[:space:]]*#/d' -e '/^[[:space:]]*$/d' "$MAIN_CRON"
    sed -e '/^[[:space:]]*#/d' -e '/^[[:space:]]*$/d' "$AI_CRON"
    printf '%s\n' "$CRON_END"
} > "$next_cron"

crontab -u www "$next_cron"
systemctl enable --now supervisor
/usr/local/bin/supervisorctl reread
/usr/local/bin/supervisorctl update

echo "Sifangda project Cron and Supervisor configuration enabled from project directories."
