#!/usr/bin/env bash
# Minimal helper: repoint multiportal.service + root cron to the correct install dir.
set -euo pipefail
[[ $EUID -eq 0 ]] || { echo "Please run with sudo/root."; exit 1; }

TARGET="${1:-}"

# 1) Detect install dir (has 'yii' + 'backend/web')
if [[ -z "${TARGET}" ]]; then
  TARGET="$(find /var/www -maxdepth 2 -type f -name yii -printf '%h\n' 2>/dev/null \
            | while read -r d; do [[ -d "$d/backend/web" ]] && echo "$d"; done \
            | grep -E '/var/www/(multiportal|.+\.dc\.arcnet\.tech)$' \
            | head -n1 || true)"
fi
[[ -n "$TARGET" && -f "$TARGET/yii" && -d "$TARGET/backend/web" ]] \
  || { echo "Could not detect a valid install (need /var/www/... with 'yii' + 'backend/web')."; exit 1; }

echo "Using install dir: $TARGET"

# 2) Update systemd unit
UNIT="/etc/systemd/system/multiportal.service"
if [[ -f "$UNIT" ]]; then
  cp -a "$UNIT" "$UNIT.bak.$(date +%s)"
  # Ensure [Service] has WorkingDirectory + ExecStart pointing to TARGET
  sed -i -E \
    -e "s#^WorkingDirectory=.*#WorkingDirectory=$TARGET#g" \
    -e "s#^ExecStart=.*#ExecStart=/usr/bin/php $TARGET/yii queue/listen --verbose#g" \
    "$UNIT" || true
  grep -q '^WorkingDirectory=' "$UNIT" || sed -i "/^\[Service\]/a WorkingDirectory=$TARGET" "$UNIT"
  grep -q '^ExecStart=' "$UNIT" || sed -i "/^\[Service\]/a ExecStart=/usr/bin/php $TARGET/yii queue/listen --verbose" "$UNIT"

  systemctl daemon-reload
  systemctl restart multiportal.service || true
  systemctl status multiportal.service --no-pager -l || true
else
  echo "Note: $UNIT not found, skipping systemd update."
fi

# 3) Fix root crontab entry for ./yii cron (replace or append)
CURRENT_CRON="$(mktemp)"
crontab -l 2>/dev/null > "$CURRENT_CRON" || true
NEW_CRON="$(mktemp)"
# Replace any existing MP cron line; if none, append a correct one.
if grep -qE 'cd /var/www/.+ && ./yii cron' "$CURRENT_CRON"; then
  sed -E "s#cd /var/www/[^ ]+ && \./yii cron#cd $TARGET \&\& ./yii cron#g" "$CURRENT_CRON" > "$NEW_CRON"
else
  cat "$CURRENT_CRON" > "$NEW_CRON"
  echo "* * * * * cd $TARGET && ./yii cron" >> "$NEW_CRON"
fi
crontab "$NEW_CRON"
rm -f "$CURRENT_CRON" "$NEW_CRON"

echo "All set. Verified path: $TARGET"
echo "If the service still misbehaves, please share:"
echo "  sudo systemctl status multiportal.service"
echo "  sudo journalctl -u multiportal.service -n 100 --no-pager"

