#!/usr/bin/env bash
# Minimal helper: repoint MultiPortal Worker service + 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 \
            | 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"

# Extract and validate HOST_NAME from .env
ENV_FILE="$TARGET/.env"
HOST_NAME=""
DIR_NAME="$(basename "$TARGET")"
HOST_MATCH="true"

if [[ -f "$ENV_FILE" ]]; then
  # Extract HOST_NAME value (handles both quoted and unquoted values)
  HOST_NAME="$(grep -E '^HOST_NAME=' "$ENV_FILE" 2>/dev/null | sed -E 's/^HOST_NAME=["'\'']*([^"'\'']+)["'\'']*$/\1/' || true)"
  
  if [[ -n "$HOST_NAME" ]]; then
    echo "Found HOST_NAME in .env: $HOST_NAME"
    if [[ "$HOST_NAME" != "$DIR_NAME" ]]; then
      HOST_MATCH="False"
      echo ""
      echo "HOST_NAME mismatch"
      echo "   Directory name: $DIR_NAME"
      echo "   HOST_NAME in .env: $HOST_NAME"
      echo ""
    fi
  else
    echo "WARNING: No HOST_NAME found in .env file"
    HOST_MATCH="?"
  fi
else
  echo "WARNING: No .env file found at $ENV_FILE"
  HOST_MATCH="?"
fi

# Confirmation prompt
echo ""
echo "This script will:"
echo "  - Update multiportal.service to use: $TARGET"
echo "  - Update worker to use: $TARGET"
echo "  - Update root crontab to use: $TARGET"
if [[ "$HOST_MATCH" == "False" || "$HOST_MATCH" == "?" ]]; then
  echo "  - Update HOST_NAME in .env to: $DIR_NAME"
fi
if [[ -n "$HOST_NAME" ]]; then
  if [[ "$HOST_MATCH" == "true" ]]; then
    echo "  - HOST_NAME validation: OK (Directory: $DIR_NAME, .env: $HOST_NAME)"
  else
    echo "  - HOST_NAME validation: MISMATCH (Directory: $DIR_NAME, .env: $HOST_NAME)"
  fi
fi
echo ""

if [[ "$HOST_MATCH" == "False" ]]; then
  echo "   The HOST_NAME in .env doesn't match the directory name."
  echo "   It will be updated to match."
  echo ""
fi

read -p "Do you want to continue? (y/N): " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Aborted."
    exit 0
fi

# Update HOST_NAME in .env if needed
if [[ -f "$ENV_FILE" ]]; then
  if [[ "$HOST_MATCH" == "False" || "$HOST_MATCH" == "?" ]]; then
    echo "Updating HOST_NAME in .env..."
    # Backup the .env file
    cp -a "$ENV_FILE" "$ENV_FILE.bak.$(date +%s)"
    
    if grep -q '^HOST_NAME=' "$ENV_FILE"; then
      # Replace existing HOST_NAME
      sed -i -E "s/^HOST_NAME=.*/HOST_NAME=\"$DIR_NAME\"/" "$ENV_FILE"
      echo "Updated existing HOST_NAME to: $DIR_NAME"
    else
      # Add HOST_NAME if it doesn't exist
      echo "HOST_NAME=\"$DIR_NAME\"" >> "$ENV_FILE"
      echo "Added HOST_NAME: $DIR_NAME"
    fi
  fi
elif [[ "$HOST_MATCH" == "?" ]]; then
  echo "Creating .env file with HOST_NAME..."
  echo "HOST_NAME=\"$DIR_NAME\"" > "$ENV_FILE"
  echo "Created .env with HOST_NAME: $DIR_NAME"
fi

# 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) Update Worker Unit
UNIT="/etc/systemd/system/multiportal-queue@.service"
if [[ -f "$UNIT" ]]; then
  echo "Updating Worker Service"
  php $TARGET/yii queue-service/stop "*"
  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
  php $TARGET/yii queue-service/start 1
  php $TARGET/yii queue-service/start 2
else
  echo "Note: $UNIT not found, skipping systemd update."
fi

# 4) 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"

