#!/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="zicaiduck"
SERVER_URL="https://upload.zhendaojishu.com"
DOWNLOAD_URL="${SERVER_URL}/${TOOL_NAME}.txz"
INSTALL_DIR=/usr/local/share/pentakill

# ===================== 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
}

# 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} file 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

  
  if [ "$IS_UPGRADE" = "true" ]; then
    info "Backup existing license file..."
    if [ -f "$INSTALL_DIR/www/zicaibird/zicaibird.lic" ]; then
      cp "$INSTALL_DIR/www/zicaibird/zicaibird.lic" "$TMP_DIR/zicaibird.lic"
    fi
  fi
  
  ls "$TMP_DIR"
  # Install www to target directory
  info "Installing www to ${INSTALL_DIR}..."
  if [ -d "$TMP_DIR/www" ]; then
    run_with_privilege cp -Rf "$TMP_DIR/www" "$INSTALL_DIR/"
  else
    red "Error: www not found in package!"
    rm -rf "$TMP_DIR"
    exit 1
  fi
  # Install self_signed_certs to target directory
  info "Installing self_signed_certs to ${INSTALL_DIR}..."
  if [ -d "$TMP_DIR/self_signed_certs" ]; then
    run_with_privilege cp -Rf "$TMP_DIR/self_signed_certs" "$INSTALL_DIR/"
  else
    red "Error: self_signed_certs not found in package!"
    rm -rf "$TMP_DIR"
    exit 1
  fi
  
  if [ "$IS_UPGRADE" = "true" ]; then
    run_with_privilege cp -f "$TMP_DIR/zicaibird.lic" "$INSTALL_DIR/www/zicaibird/zicaibird.lic"
    green "${TOOL_NAME} updated successfully!"
  else
    # Install config.toml to target directory
    info "Installing config.toml to ${INSTALL_DIR}..."
    if [ -f "$TMP_DIR/config.toml" ]; then
      run_with_privilege cp -f "$TMP_DIR/config.toml" "$INSTALL_DIR/"
    else
      red "Error: config.toml not found in package!"
      rm -rf "$TMP_DIR"
      exit 1
    fi
    green "${TOOL_NAME} installed successfully!"
  fi
}

# Display usage information
show_usage() {
  echo "Usage: $0 [options]"
  echo ""
  echo "Options:"
  echo "  --file FILE   Install from offline package file"
  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"
}

# ===================== 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
        ;;
      --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 [ -f "${INSTALL_DIR}/config.toml" ]; then
    yellow "${TOOL_NAME} is already installed, performing upgrade..."
    IS_UPGRADE="true"
  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"
  
  # Clean up temporary files
  rm -rf "$TMP_DIR"
  
  # Verify installation
  info "Verifying installation..."
  if [ -f "${INSTALL_DIR}/config.toml" ]; then
    if [ "$IS_UPGRADE" = "true" ]; then
      green "===== Upgrade successful! ====="
    else
      green "===== Installation successful! ====="
    fi
  else
    red "===== Installation failed! ====="
    red "Please manually check if ${INSTALL_DIR} is in your PATH."
    exit 1
  fi
}

# Execute main logic
main "$@"
