#!/bin/bash
set -e

APP_DIR=/opt/irc-bot
DATA_DIR=/var/lib/irc-bot
LOG_DIR=/var/log/irc-bot
CONF_DIR=/etc/irc-bot
USER=irc-bot
GROUP=irc-bot

case "$1" in
  configure)
    # Create system user/group if they don't exist
    if ! getent group "$GROUP" > /dev/null 2>&1; then
      addgroup --system "$GROUP"
    fi
    if ! getent passwd "$USER" > /dev/null 2>&1; then
      adduser --system --ingroup "$GROUP" --no-create-home \
              --home "$DATA_DIR" --shell /usr/sbin/nologin "$USER"
    fi

    # Runtime directories
    install -d -m 750 -o "$USER" -g "$GROUP" "$DATA_DIR"
    install -d -m 750 -o "$USER" -g "$GROUP" "$DATA_DIR/history"
    install -d -m 750 -o "$USER" -g "$GROUP" "$LOG_DIR"

    # Config directory — preserve existing .env if present
    install -d -m 750 -o "$USER" -g "$GROUP" "$CONF_DIR"
    if [ ! -f "$CONF_DIR/.env" ]; then
      cp "$APP_DIR/.env.example" "$CONF_DIR/.env"
      chown "$USER:$GROUP" "$CONF_DIR/.env"
      chmod 640 "$CONF_DIR/.env"
      echo ""
      echo "  ┌─────────────────────────────────────────────────────┐"
      echo "  │  irc-bot: edit /etc/irc-bot/.env before starting   │"
      echo "  │  Set ZNC_USER, ZNC_PASSWORD, ZNC_NETWORK at minimum │"
      echo "  └─────────────────────────────────────────────────────┘"
      echo ""
    fi

    # Symlink runtime directories into app dir so relative paths work
    ln -sfn "$DATA_DIR"   "$APP_DIR/data"
    ln -sfn "$LOG_DIR"    "$APP_DIR/logs"
    ln -sfn "$CONF_DIR"   "$APP_DIR/config"

    # Install Python venv with dependencies
    if [ ! -d "$APP_DIR/venv" ]; then
      echo "irc-bot: creating Python venv and installing dependencies..."
      python3 -m venv "$APP_DIR/venv"
      "$APP_DIR/venv/bin/pip" install --quiet --no-cache-dir -r "$APP_DIR/requirements.txt"
      chown -R "$USER:$GROUP" "$APP_DIR/venv"
    fi

    # Enable and start systemd services
    if [ -d /run/systemd/system ]; then
      systemctl daemon-reload
      systemctl enable irc-bot.service irc-bot-portal.service
      echo "irc-bot: services enabled. Start with:"
      echo "  systemctl start irc-bot irc-bot-portal"
    fi
    ;;
esac

exit 0
