#!/bin/bash
#
# zyhk_sio_client 部署安装脚本
# 支持: 全新安装 / 覆盖更新
# 用法: sudo ./install.sh [--force-config]
#

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PKG_DIR="${1:-$SCRIPT_DIR}"
INSTALL_DIR="/opt/zyhk_sio_client"
USER_NAME="zyhk"
GROUP_NAME="zyhk"
FORCE_CONFIG=false
WAS_RUNNING=false

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

info()  { echo -e "${BLUE}[INFO]${NC}  $*"; }
ok()    { echo -e "${GREEN}[OK]${NC}   $*"; }
warn()  { echo -e "${YELLOW}[WARN]${NC} $*"; }
err()   { echo -e "${RED}[ERR]${NC}  $*"; }

check_root() {
    if [ "$EUID" -ne 0 ]; then
        err "Please run as root: sudo $0"
        exit 1
    fi
}

parse_args() {
    for arg in "$@"; do
        case "$arg" in
            --force-config) FORCE_CONFIG=true ;;
            -h|--help)
                echo "Usage: sudo $0 [--force-config]"
                echo ""
                echo "Options:"
                echo "  --force-config  Overwrite existing config.json (default: keep old, save new as .new)"
                echo "  -h, --help      Show this help"
                exit 0
                ;;
        esac
    done
}

create_user() {
    if ! id -u "$USER_NAME" &>/dev/null; then
        info "Creating user: $USER_NAME"
        useradd --system --no-create-home --shell /usr/sbin/nologin "$USER_NAME"
        ok "User $USER_NAME created"
    else
        ok "User $USER_NAME already exists"
    fi
}

install_files() {
    info "Installing to $INSTALL_DIR ..."
    mkdir -p "$INSTALL_DIR"/{bin,config,logs,tmp}

    # Binary: always overwrite
    if [ -f "$PKG_DIR/build/zyhk_sio_client" ]; then
        cp -f "$PKG_DIR/build/zyhk_sio_client" "$INSTALL_DIR/bin/"
        chmod 755 "$INSTALL_DIR/bin/zyhk_sio_client"
    elif [ -f "$PKG_DIR/zyhk_sio_client" ]; then
        cp -f "$PKG_DIR/zyhk_sio_client" "$INSTALL_DIR/bin/"
        chmod 755 "$INSTALL_DIR/bin/zyhk_sio_client"
    else
        err "Binary not found in $PKG_DIR"
        exit 1
    fi
    ok "Binary updated"

    # Config
    if [ -f "$PKG_DIR/config/config.json" ]; then
        if [ "$FORCE_CONFIG" = true ]; then
            cp -f "$PKG_DIR/config/config.json" "$INSTALL_DIR/config/config.json"
            ok "Config overwritten (--force-config)"
        elif [ ! -f "$INSTALL_DIR/config/config.json" ]; then
            cp "$PKG_DIR/config/config.json" "$INSTALL_DIR/config/config.json"
            ok "Config installed (new)"
        else
            cp "$PKG_DIR/config/config.json" "$INSTALL_DIR/config/config.json.new"
            ok "Config kept existing, new version saved as config.json.new"
        fi
    fi

    # Libraries: always overwrite
    if [ -d "$PKG_DIR/lib" ]; then
        mkdir -p "$INSTALL_DIR/lib"
        cp -rf "$PKG_DIR/lib"/* "$INSTALL_DIR/lib/" 2>/dev/null || true
        ok "Libraries updated"
    fi

    # Ownership
    chown -R "$USER_NAME:$GROUP_NAME" "$INSTALL_DIR"
    chmod 750 "$INSTALL_DIR"
    chmod 755 "$INSTALL_DIR/bin"
    chmod 770 "$INSTALL_DIR/logs"
    chmod 770 "$INSTALL_DIR/tmp"

    ok "Files installed to $INSTALL_DIR"
}

install_systemd() {
    if command -v systemctl &>/dev/null; then
        # Check if service was running before update
        if systemctl is-active --quiet zyhk-sio-client 2>/dev/null; then
            WAS_RUNNING=true
            info "Service is running, stopping for update..."
            systemctl stop zyhk-sio-client
        fi

        info "Installing systemd service..."
        cp -f "$SCRIPT_DIR/zyhk-sio-client.service" /etc/systemd/system/
        systemctl daemon-reload
        ok "Systemd service updated"

        # Restart if it was running
        if [ "$WAS_RUNNING" = true ]; then
            info "Restarting service..."
            systemctl start zyhk-sio-client
            ok "Service restarted"
        fi
    else
        warn "systemctl not found, skipping systemd service installation"
    fi
}

install_deps() {
    info "Checking runtime dependencies..."
    local missing=()
    for pkg in libmosquitto1 libcurl4; do
        if ! dpkg -l "$pkg" &>/dev/null 2>&1; then
            missing+=("$pkg")
        fi
    done
    if [ ${#missing[@]} -gt 0 ]; then
        warn "Missing runtime packages: ${missing[*]}"
        warn "Install with: sudo apt-get install -y ${missing[*]}"
    else
        ok "Runtime dependencies OK"
    fi
}

print_summary() {
    echo ""
    ok "Installation complete"
    echo ""
    echo "  Install dir: $INSTALL_DIR"
    echo "  Binary:      $INSTALL_DIR/bin/zyhk_sio_client"
    echo "  Config:      $INSTALL_DIR/config/config.json"
    echo "  Logs:        journalctl -u zyhk-sio-client -f"
    echo "  Data dir:    $INSTALL_DIR"
    echo ""
    if [ "$WAS_RUNNING" = true ]; then
        echo "  Service:     restarted automatically"
    else
        echo "  Start:       sudo systemctl start zyhk-sio-client"
    fi
    echo "  Status:      sudo systemctl status zyhk-sio-client"
    echo "  Debug web:   http://localhost:18080/"
    echo ""
}

parse_args "$@"
check_root
create_user
install_files
install_systemd
install_deps
print_summary
