#!/bin/bash
# PNANA Package Installation Script
# Install PNANA from extracted package archive
#
# Usage: ./package_install.sh [options]
#
# This script is automatically generated by CMake during build

set -e  # 遇到错误立即退出

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Show help information
show_help() {
    echo "PNANA Package Installation Script"
    echo "Install PNANA from extracted package archive"
    echo ""
    echo "Usage: $0 [OPTIONS]"
    echo ""
    echo "Options:"
    echo "  -h, --help          Show this help message"
    echo "  -p, --prefix DIR    Installation prefix (default: auto-detect)"
    echo "  --system             Install system-wide (requires sudo)"
    echo "  --user               Install for current user only"
    echo "  --no-config          Skip configuration file installation"
    echo "  --no-plugins         Skip plugin installation"
    echo "  --dry-run            Show what would be installed without doing it"
    echo ""
    echo "Examples:"
    echo "  $0                    # Auto-detect installation type"
    echo "  $0 --system          # System-wide installation (requires sudo)"
    echo "  $0 --user            # User-only installation"
    echo "  $0 --dry-run         # Show what would be installed"
    echo ""
    echo "This script installs PNANA from the current directory."
}

# 解析命令行参数
INSTALL_TYPE="auto"
SKIP_CONFIG=false
SKIP_PLUGINS=false
DRY_RUN=false
CUSTOM_PREFIX=""

while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            show_help
            exit 0
            ;;
        -p|--prefix)
            CUSTOM_PREFIX="$2"
            shift 2
            ;;
        --system)
            INSTALL_TYPE="system"
            shift
            ;;
        --user)
            INSTALL_TYPE="user"
            shift
            ;;
        --no-config)
            SKIP_CONFIG=true
            shift
            ;;
        --no-plugins)
            SKIP_PLUGINS=true
            shift
            ;;
        --dry-run)
            DRY_RUN=true
            shift
            ;;
        *)
            log_error "Unknown option: $1"
            show_help
            exit 1
            ;;
    esac
done

# Check current directory structure
if [ ! -d "bin" ] || [ ! -d "share" ]; then
    log_error "This script must be run from the extracted PNANA package directory."
    log_info "The directory should contain 'bin' and 'share' subdirectories."
    log_info "Example: cd pnana-0.0.4 && ./package_install.sh"
    exit 1
fi

if [ ! -f "bin/pnana" ]; then
    log_error "PNANA executable not found in bin/pnana"
    exit 1
fi

log_info "Detected PNANA package in current directory"
log_info "Installation type: $INSTALL_TYPE"

# 检测用户和权限
CURRENT_USER="${USER:-$(whoami)}"
if [ "$EUID" -eq 0 ]; then
    IS_ROOT=true
    log_info "Running with root privileges"
else
    IS_ROOT=false
    log_info "Running as regular user: $CURRENT_USER"
fi

# 确定安装类型
if [ "$INSTALL_TYPE" = "auto" ]; then
    if [ "$IS_ROOT" = true ]; then
        INSTALL_TYPE="system"
        log_info "Auto-detected: System-wide installation"
    else
        INSTALL_TYPE="user"
        log_info "Auto-detected: User-only installation"
    fi
fi

# Validate installation type
if [ "$INSTALL_TYPE" = "system" ] && [ "$IS_ROOT" = false ]; then
    log_error "System installation requires root privileges. Use 'sudo $0 --system' or run '$0 --user'"
    exit 1
fi

# 设置安装路径
if [ "$INSTALL_TYPE" = "system" ]; then
    BINARY_DEST="/usr/local/bin/pnana"
    CONFIG_DEST="/etc/pnana"
    PLUGIN_DEST="/usr/local/share/pnana/plugins"
    DATA_DEST="/usr/local/share/pnana"
elif [ "$INSTALL_TYPE" = "user" ]; then
    BINARY_DEST="$HOME/.local/bin/pnana"
    CONFIG_DEST="$HOME/.config/pnana"
    PLUGIN_DEST="$HOME/.config/pnana/plugins"
    DATA_DEST="$HOME/.local/share/pnana"
fi

# 如果指定了自定义前缀
if [ -n "$CUSTOM_PREFIX" ]; then
    BINARY_DEST="$CUSTOM_PREFIX/bin/pnana"
    CONFIG_DEST="$CUSTOM_PREFIX/etc/pnana"
    PLUGIN_DEST="$CUSTOM_PREFIX/share/pnana/plugins"
    DATA_DEST="$CUSTOM_PREFIX/share/pnana"
    log_info "Using custom prefix: $CUSTOM_PREFIX"
fi

# 显示安装计划
log_info "Installation plan:"
echo "  Binary: bin/pnana -> $BINARY_DEST"
if [ "$SKIP_CONFIG" = false ]; then
    echo "  Config: share/pnana/default_config.json -> $CONFIG_DEST/config.json"
fi
if [ "$SKIP_PLUGINS" = false ] && [ -d "share/pnana/plugins" ]; then
    echo "  Plugins: share/pnana/plugins/ -> $PLUGIN_DEST/"
fi

if [ "$DRY_RUN" = true ]; then
    log_info "Dry run completed. Use without --dry-run to perform actual installation."
    exit 0
fi

# Create destination directories
log_info "Creating destination directories..."
if [ "$INSTALL_TYPE" = "system" ]; then
    mkdir -p "$(dirname "$BINARY_DEST")" 2>/dev/null || true
    mkdir -p "$CONFIG_DEST" 2>/dev/null || true
    mkdir -p "$PLUGIN_DEST" 2>/dev/null || true
    mkdir -p "$DATA_DEST" 2>/dev/null || true
else
    mkdir -p "$(dirname "$BINARY_DEST")"
    mkdir -p "$CONFIG_DEST"
    mkdir -p "$PLUGIN_DEST"
    mkdir -p "$DATA_DEST"
fi

# Install binary file
log_info "Installing executable..."
cp "bin/pnana" "$BINARY_DEST"
chmod 755 "$BINARY_DEST"
log_success "Executable installed: $BINARY_DEST"

# Install configuration file
if [ "$SKIP_CONFIG" = false ]; then
    log_info "Installing configuration..."
    if [ -f "share/pnana/default_config.json" ]; then
        cp "share/pnana/default_config.json" "$CONFIG_DEST/config.json"
        log_success "Configuration installed: $CONFIG_DEST/config.json"
    else
        log_warning "Default configuration file not found"
    fi
fi

# 安装插件
if [ "$SKIP_PLUGINS" = false ] && [ -d "share/pnana/plugins" ]; then
    log_info "Installing plugins..."
    cp -r "share/pnana/plugins/"* "$PLUGIN_DEST/" 2>/dev/null || true
    log_success "Plugins installed: $PLUGIN_DEST/"
fi

# 设置环境变量（对于用户安装）
if [ "$INSTALL_TYPE" = "user" ]; then
    log_info "Setting up environment..."

    # 检查 PATH 中是否包含 ~/.local/bin
    if [[ ":$PATH:" != *":$HOME/.local/bin:"* ]]; then
        SHELL_RC=""
        if [ -f "$HOME/.bashrc" ]; then
            SHELL_RC="$HOME/.bashrc"
        elif [ -f "$HOME/.zshrc" ]; then
            SHELL_RC="$HOME/.zshrc"
        fi

        if [ -n "$SHELL_RC" ]; then
            if ! grep -q 'export PATH="$HOME/.local/bin:$PATH"' "$SHELL_RC" 2>/dev/null; then
                echo 'export PATH="$HOME/.local/bin:$PATH"' >> "$SHELL_RC"
                log_info "Added ~/.local/bin to PATH in $SHELL_RC"
                log_info "Run 'source $SHELL_RC' or restart your terminal to use 'pnana' command"
            fi
        fi
    fi
fi

# Verify installation
log_info "Verifying installation..."
if [ -x "$BINARY_DEST" ]; then
    log_success "✓ PNANA executable: $BINARY_DEST"

    # 测试运行
    if "$BINARY_DEST" --version >/dev/null 2>&1; then
        log_success "✓ PNANA is working correctly"
    else
        log_warning "⚠ PNANA executable found but may not be working properly"
    fi
else
    log_error "✗ PNANA executable not found or not executable"
    exit 1
fi

if [ "$SKIP_CONFIG" = false ] && [ -f "$CONFIG_DEST/config.json" ]; then
    log_success "✓ Configuration file: $CONFIG_DEST/config.json"
fi

if [ "$SKIP_PLUGINS" = false ] && [ -d "$PLUGIN_DEST" ]; then
    PLUGIN_COUNT=$(find "$PLUGIN_DEST" -type f 2>/dev/null | wc -l)
    log_success "✓ Plugins directory: $PLUGIN_DEST ($PLUGIN_COUNT files)"
fi

# 完成
log_success "PNANA installation completed!"

echo ""
log_info "To start PNANA:"
if [ "$INSTALL_TYPE" = "system" ]; then
    echo "  pnana"
else
    echo "  $BINARY_DEST"
    echo "  Or run 'pnana' after restarting your terminal"
fi

if [ "$INSTALL_TYPE" = "user" ] && [[ ":$PATH:" != *":$HOME/.local/bin:"* ]]; then
    echo ""
    log_info "Important: Restart your terminal or run 'source ~/.bashrc' to update PATH"
fi

exit 0
