#!/usr/bin/env bash
# Script name: install.sh
# Purpose: One-click installation and uninstallation
# Compatibility: Linux (Ubuntu/Debian/CentOS)

# ===================== Core Configuration (Editable) =====================
# Tool name
TOOL_NAME="mushgui"
# Installation directory
INSTALL_DIR="/usr/local/bin"
# Config directory
CONFIG_DIR="/etc/${TOOL_NAME}"
# systemd service name
SERVICE_NAME="${TOOL_NAME}.service"

ARCH=$(uname -m)
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
case "$ARCH" in
    x86_64)
      TARGET_ARCH="x86_64"
      ;;
    aarch64|arm64)
      TARGET_ARCH="aarch64"
      ;;
    *)
      red "Error: Unsupported architecture: $ARCH"
      exit 1
      ;;
esac
SERVER_URL="https://upload.zhendaojishu.com"
DOWNLOAD_URL="${SERVER_URL}/${TOOL_NAME}-${TARGET_ARCH}.txz"

# ===================== Configuration Templates (Editable) =====================
# Default configuration file content
DEFAULT_CONFIG="# Mushgui Configuration File
# Modify these settings according to your environment

# License file path
# HDC_LICENSE_FILE_PATH=/usr/local/share/${TOOL_NAME}/${TOOL_NAME}.lic

# UDP bind address
# HDC_UDP_BIND_ADDR=0.0.0.0:7299

# Rust log level
RUST_LOG=${TOOL_NAME}=info"

# Systemd service file content
SYSTEMD_SERVICE="[Unit]
Description=${TOOL_NAME}
After=network.target

[Service]
Type=simple
User=root
Group=root
EnvironmentFile=${CONFIG_DIR}/${TOOL_NAME}.conf
ExecStart=${INSTALL_DIR}/${TOOL_NAME} start
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target"

# ===================== Helper Functions (No Modification Needed) =====================
# Colored output (enhanced user experience)
red() { echo -e "\033[31m$1\033[0m"; }
green() { echo -e "\033[32m$1\033[0m"; }
yellow() { echo -e "\033[33m$1\033[0m"; }
info() { echo -e "\033[36m$1\033[0m"; }

# Check if command exists
check_command() {
  if ! command -v "$1" >/dev/null 2>&1; then
    red "Error: Required command $1 is missing, please install it first!"
    exit 1
  fi
}

# Check permissions (root required for system directory installation)
check_permission() {
  if [ "$(id -u)" -ne 0 ]; then
    yellow "Warning: Operation requires root privileges, will try to use sudo..."
    if ! command -v sudo >/dev/null 2>&1; then
      red "Error: No sudo permission available!"
      exit 1
    fi
  fi
}

# Run command with sudo if not root
run_with_privilege() {
  if [ "$(id -u)" -eq 0 ]; then
    "$@"
  else
    sudo "$@"
  fi
}

# Check if system uses systemd
check_systemd() {
  if command -v systemctl >/dev/null 2>&1; then
    return 0
  else
    return 1
  fi
}

# Check if tool is already installed
check_existing_installation() {
  if command -v "${INSTALL_DIR}/${TOOL_NAME}" >/dev/null 2>&1; then
    return 0
  else
    return 1
  fi
}

# Stop service if it's running
stop_service() {
  if check_systemd; then
    if run_with_privilege systemctl status "$SERVICE_NAME" >/dev/null 2>&1; then
      info "Stopping existing ${SERVICE_NAME} service..."
      run_with_privilege systemctl stop "$SERVICE_NAME"
      green "Service stopped successfully"
    fi
  fi
}

# Create default configuration file
create_default_config() {
  info "Creating default configuration file..."
  
  run_with_privilege mkdir -p "$CONFIG_DIR"
  
  # Create config file with proper variable expansion
  run_with_privilege bash -c "cat > '$CONFIG_DIR/${TOOL_NAME}.conf' << 'EOF'
$DEFAULT_CONFIG
EOF"
  
  green "Default configuration created at $CONFIG_DIR/${TOOL_NAME}.conf"
  yellow "Please edit the configuration file to match your environment before starting the service!"
}

# Install systemd service
install_systemd_service() {
  if check_systemd; then
    info "Installing systemd service..."
    
    # Create systemd service file
    run_with_privilege tee "/etc/systemd/system/${SERVICE_NAME}" > /dev/null << EOF
$SYSTEMD_SERVICE
EOF
    
    # Reload systemd configuration
    run_with_privilege systemctl daemon-reload
    run_with_privilege systemctl enable "${SERVICE_NAME}"
    
    green "systemd service installed successfully!"
    info "Start service with: sudo systemctl start ${SERVICE_NAME}"
    info "Check status with: sudo systemctl status ${SERVICE_NAME}"
  else
    yellow "Warning: Current system does not support systemd, skipping service installation."
  fi
}

# Download and install binary
install_binary() {
  local TMP_DIR="$1"
  local IS_UPGRADE="$2"
  local OFFLINE_FILE="$3"
  
  if [ -n "$OFFLINE_FILE" ]; then
    # Use offline package
    info "Using offline package: $OFFLINE_FILE"
    
    if [ ! -f "$OFFLINE_FILE" ]; then
      red "Error: Offline package not found: $OFFLINE_FILE"
      exit 1
    fi
    
    # Copy offline file to temp directory
    cp "$OFFLINE_FILE" "$TMP_DIR/${TOOL_NAME}.txz"
  else
    # Download from internet
    info "Downloading ${TOOL_NAME} binary from $DOWNLOAD_URL ..."
    
    # Try to download from GitHub releases or local build
    
    if ! curl -fSL --progress-bar "$DOWNLOAD_URL" -o "$TMP_DIR/${TOOL_NAME}.txz"; then
      red "Download failed"
      exit 1
    fi
  fi
  
  # Extract downloaded archive
  if [ -f "$TMP_DIR/${TOOL_NAME}.txz" ]; then
    info "Extracting installation package..."
    if ! tar -xJf "$TMP_DIR/${TOOL_NAME}.txz" -C "$TMP_DIR"; then
      red "Error: Extraction failed! Package may be corrupted."
      rm -rf "$TMP_DIR"
      exit 1
    fi
  fi
  
  # Install binary to target directory
  info "Installing binary to ${INSTALL_DIR}..."
  if [ -f "$TMP_DIR/${TOOL_NAME}" ]; then
    run_with_privilege cp -f "$TMP_DIR/${TOOL_NAME}" "$INSTALL_DIR/"
  else
    red "Error: Binary not found in package!"
    rm -rf "$TMP_DIR"
    exit 1
  fi
  
  # Add executable permission
  run_with_privilege chmod +x "${INSTALL_DIR}/${TOOL_NAME}"
  
  if [ "$IS_UPGRADE" = "true" ]; then
    green "Binary updated successfully!"
  else
    green "Binary installed successfully!"
  fi
}

# Start service after installation/upgrade
start_service() {
  if check_systemd; then
    info "Starting ${SERVICE_NAME} service..."
    run_with_privilege systemctl start "$SERVICE_NAME"
    green "Service started successfully!"
    info "Check status with: sudo systemctl status ${SERVICE_NAME}"
  fi
}

# Uninstall tool
uninstall() {
  info "===== Starting uninstallation of ${TOOL_NAME} ===="
  
  # Check if installed
  if ! check_existing_installation; then
    red "Error: ${TOOL_NAME} is not installed!"
    exit 1
  fi
  
  # Stop service if running
  stop_service
  
  # Disable and remove systemd service
  if check_systemd; then
    if [ -f "/etc/systemd/system/${SERVICE_NAME}" ]; then
      info "Removing systemd service..."
      run_with_privilege systemctl disable "$SERVICE_NAME" 2>/dev/null
      run_with_privilege rm -f "/etc/systemd/system/${SERVICE_NAME}"
      run_with_privilege systemctl daemon-reload
      green "Systemd service removed successfully!"
    fi
  fi
  
  # Remove binary
  if [ -f "${INSTALL_DIR}/${TOOL_NAME}" ]; then
    info "Removing binary from ${INSTALL_DIR}..."
    run_with_privilege rm -f "${INSTALL_DIR}/${TOOL_NAME}"
    green "Binary removed successfully!"
  fi
  
  # Remove configuration directory
  if [ -d "$CONFIG_DIR" ]; then
    info "Removing configuration directory..."
    run_with_privilege rm -rf "$CONFIG_DIR"
    green "Configuration directory removed successfully!"
  fi
  
  # Verify uninstallation
  if ! check_existing_installation; then
    green "===== Uninstallation successful! ====="
    info "${TOOL_NAME} has been completely removed from your system."
  else
    red "===== Uninstallation failed! ====="
    red "Some components may still be present. Please check manually."
    exit 1
  fi
}

# Display usage information
show_usage() {
  echo "Usage: $0 [options]"
  echo ""
  echo "Options:"
  echo "  --file FILE   Install from offline package file"
  echo "  --uninstall   Uninstall ${TOOL_NAME} from the system"
  echo "  --help        Show this help message"
  echo ""
  echo "Examples:"
  echo "  # Install or upgrade ${TOOL_NAME} (download from internet)"
  echo "  $0"
  echo ""
  echo "  # Install from offline package"
  echo "  $0 --file ./${TOOL_NAME}-x86_64.txz"
  echo ""
  echo "  # Uninstall ${TOOL_NAME}"
  echo "  $0 --uninstall"
}

# ===================== Main Logic =====================
main() {
  local OFFLINE_FILE=""
  
  # Parse command line arguments
  while [ $# -gt 0 ]; do
    case "$1" in
      --file)
        if [ -n "$2" ] && [ "${2#--}" = "$2" ]; then
          OFFLINE_FILE="$2"
          shift 2
        else
          red "Error: --file requires a file path argument"
          exit 1
        fi
        ;;
      --uninstall)
        check_permission
        uninstall
        exit 0
        ;;
      --help)
        show_usage
        exit 0
        ;;
      *)
        red "Error: Unknown option: $1"
        show_usage
        exit 1
        ;;
    esac
  done
  
  # Default behavior: install or upgrade
  info "===== Starting installation of ${TOOL_NAME} ===="
  
  # Check required dependencies
  info "Checking required commands..."
  if [ -z "$OFFLINE_FILE" ]; then
    # Only need curl for online installation
    check_command "curl"
  fi
  check_command "tar"
  
  # Check permissions
  check_permission
  
  # Check if already installed
  local IS_UPGRADE="false"
  if check_existing_installation; then
    yellow "${TOOL_NAME} is already installed, performing upgrade..."
    IS_UPGRADE="true"
    
    # Stop service if running
    stop_service
  fi
  
  # Create temporary directory
  local TMP_DIR=$(mktemp -d)
  if [ ! -d "$TMP_DIR" ]; then
    red "Error: Failed to create temporary directory!"
    exit 1
  fi
  info "Temporary directory: $TMP_DIR"
  
  # Install binary
  install_binary "$TMP_DIR" "$IS_UPGRADE" "$OFFLINE_FILE"
  
  # Create configuration directory and default config (only if not upgrading)
  if [ "$IS_UPGRADE" = "false" ]; then
    create_default_config
  else
    yellow "Skipping configuration creation (upgrade mode)"
  fi
  
  # Install systemd service (only if not upgrading)
  if [ "$IS_UPGRADE" = "false" ]; then
    install_systemd_service
  else
    # Reload systemd configuration for upgrades
    if check_systemd; then
      info "Reloading systemd configuration..."
      run_with_privilege systemctl daemon-reload
    fi
  fi
  
  # Clean up temporary files
  rm -rf "$TMP_DIR"
  
  # Start service if upgrading
  # start_service
  
  # Verify installation
  info "Verifying installation..."
  if command -v "$TOOL_NAME" >/dev/null 2>&1; then
    if [ "$IS_UPGRADE" = "true" ]; then
      green "===== Upgrade successful! ====="
    else
      green "===== Installation successful! ====="
    fi
    info "Binary location: ${INSTALL_DIR}/${TOOL_NAME}"
    info "Config location: ${CONFIG_DIR}/${TOOL_NAME}.conf"
    info ""
    info "Next steps:"
    info "  1. Edit configuration: sudo nano ${CONFIG_DIR}/${TOOL_NAME}.conf"
    info "  2. Start service: sudo systemctl start ${SERVICE_NAME}"
    info "  3. Check status: sudo systemctl status ${SERVICE_NAME}"
    info "  4. View logs: sudo journalctl -u ${SERVICE_NAME} -f"
    info ""
    info "To uninstall: curl $SERVER_URL/install-${TOOL_NAME}.sh | bash -s -- --uninstall"
  else
    red "===== Installation failed! ====="
    red "Please manually check if ${INSTALL_DIR} is in your PATH."
    exit 1
  fi
}

# Execute main logic
main "$@"
