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

readonly CONTAINER_NAME="guokang-php74"
readonly PHP_BIN="/usr/local/php7.4/bin/php"
readonly STORE_DIR="/workspace/wwwroot/zhct_gkyy/project"
readonly AI_DIR="/workspace/wwwroot/aizhct_gkyy/project"
readonly STORE_LOG_DIR="/workspace/wwwroot/log/zhct_gkyy/cron"
readonly AI_LOG_DIR="/workspace/wwwroot/log/aizhct_gkyy/cron"

job="${1:-}"
if [[ -z "$job" ]]; then
  echo "usage: $0 <meal_order|sync_power|sync_staff_flags|equipment_heart|subsidy|subsidy_expire|export_meal_order|mqtt_face_repeat|mqtt_weigh_repeat|ai_staff_power>" >&2
  exit 64
fi

if [[ "$(/usr/bin/podman inspect -f '{{.State.Running}}' "$CONTAINER_NAME" 2>/dev/null || true)" != "true" ]]; then
  echo "$(date '+%F %T') $CONTAINER_NAME is not running" >&2
  exit 69
fi

store_php() {
  /usr/bin/podman exec --user 997:995 --workdir "$STORE_DIR" \
    "$CONTAINER_NAME" "$PHP_BIN" "$@"
}

ai_php() {
  /usr/bin/podman exec --user 997:995 --workdir "$AI_DIR" \
    "$CONTAINER_NAME" "$PHP_BIN" "$@"
}

case "$job" in
  meal_order)
    log_dir="$STORE_LOG_DIR"
    command=(store_php think MealOrder)
    ;;
  sync_power)
    log_dir="$STORE_LOG_DIR"
    command=(sync_power_minute)
    ;;
  sync_staff_flags)
    log_dir="$STORE_LOG_DIR"
    command=(store_php think sync_zhipan_staff)
    ;;
  equipment_heart)
    log_dir="$STORE_LOG_DIR"
    command=(store_php think check_equipment_heart)
    ;;
  subsidy)
    log_dir="$STORE_LOG_DIR"
    command=(store_php think Subsidy)
    ;;
  subsidy_expire)
    log_dir="$STORE_LOG_DIR"
    command=(store_php think SubsidyExpire)
    ;;
  export_meal_order)
    log_dir="$STORE_LOG_DIR"
    # Release archives do not preserve empty writable directories. Recreate the
    # export root for the active release before the application runs.
    /usr/bin/install -d -o 997 -g 995 -m 0775 "$STORE_DIR/public/static/download"
    command=(store_php think ExportMealOrder)
    ;;
  mqtt_face_repeat)
    log_dir="$STORE_LOG_DIR"
    command=(store_php think MqRepeat)
    ;;
  mqtt_weigh_repeat)
    log_dir="$STORE_LOG_DIR"
    command=(store_php think MqRepeat 1)
    ;;
  ai_staff_power)
    log_dir="$AI_LOG_DIR"
    command=(ai_php think staffPower)
    ;;
  *)
    echo "unknown guokang cron job: $job" >&2
    exit 64
    ;;
esac

/usr/bin/install -d -o 997 -g 995 -m 0770 "$log_dir"
log_file="$log_dir/${job}_$(date '+%Y%m%d').log"
touch "$log_file"
chown 997:995 "$log_file"
chmod 0660 "$log_file"
exec >>"$log_file" 2>&1

echo "$(date '+%F %T') $job start"

sync_power_minute() {
  for iteration in 1 2 3 4; do
    store_php think sync_power
    if [[ "$iteration" -lt 4 ]]; then
      sleep 15
    fi
  done
}

"${command[@]}"
echo "$(date '+%F %T') $job end"
