#!/bin/bash
remove_suffix() {
    local filename="$1"
    # 常见压缩后缀名列表
    local suffixes=(
        ".tar.gz" ".tar.bz2" ".tar.xz"
        ".gz" ".bz2" ".xz" ".zip" ".rar" ".7z"
    )
    
    # 检查是否匹配常见压缩后缀
    for suffix in "${suffixes[@]}"; do
        if [[ "$filename" == *"$suffix" ]]; then
            echo "${filename%"$suffix"}"
            return
        fi
    done
    
    # 如果没有匹配，去掉最后一个点之后的内容
    echo "${filename%.*}"
}

# Logging functions
log.warn() { echo -e "[\e[33mWARN\e[0m]:  \e[1m$*\e[0m"; }
log.error() { echo -e "[\e[31mERROR\e[0m]: \e[1m$*\e[0m"; }
log.info() { echo -e "[\e[96mINFO\e[0m]:  \e[1m$*\e[0m"; }
log.debug() { echo -e "[\e[32mDEBUG\e[0m]: \e[1m$*\e[0m"; }

log.info "This is a wrapper script for file compression tools."

# Define the available commands for extraction (prioritize gxde-shell-compressor)
declare -a EXTRACTION_TOOLS=( "deepin-compressor" "gxde-shell-compressor" "ark" "engrampa" "file-roller")

# Define the available commands for compression (prioritize deepin-compressor)
declare -a COMPRESSION_TOOLS=("deepin-compressor" "gxde-shell-compressor" "ark" "engrampa" "file-roller")

# Function to check if a command exists
command_exists() {
  command -v "$1" &>/dev/null
}

# Select the best available tool based on a list of tools
select_tool() {
  local tools=("$@")
  for tool in "${tools[@]}"; do
    if command_exists "$tool"; then
      echo "$tool"
      return
    fi
  done
  log.error "No supported tool found!"
  exit 1
}

# 解压文件
extract_file() {
  local tool="$1"
  shift
  local args=("$@")

  if [[ "${args[0]}" == *.deb ]]; then
    if command_exists "gxde-shell-compressor"; then
      log.info ".deb file detected. Use gxde-shell-compressor to override."
      echo "--------------------------------------------------------------------------"
      tool="gxde-shell-compressor"
    fi
  fi

  case "$tool" in
    "deepin-compressor")
      "$tool" "${args[@]}" extract
      ;;
    "ark")
      "$tool" "${args[@]}"
      ;;
    "engrampa")
      "$tool" -f "${args[@]}"
      ;;
    "file-roller")
      "$tool" -f "${args[@]}"
      ;;
    "gxde-shell-compressor")
      "$tool" -f "${args[@]}"
      ;;
    *)
      log.error "Unsupported tool: $tool"
      exit 1
      ;;
  esac
}

# 解压到当前目录
extract_here() {
  local tool="$1"
  shift
  local args=("$@")

  if [[ "${args[0]}" == *.deb ]]; then
    if command_exists "gxde-shell-compressor"; then
      log.info ".deb file detected. Use gxde-shell-compressor to override."
      echo "--------------------------------------------------------------------------"
      tool="gxde-shell-compressor"
    fi
  fi

  case "$tool" in
    "deepin-compressor")
      "$tool" "${args[@]}" extract_to_specifypath
      for FILE in "${args[@]}"; do
        local EXTRACT_DIR
        EXTRACT_DIR=$(dirname "$FILE")
        local TARGET_DIR="$EXTRACT_DIR/$(remove_suffix "$(basename "$FILE")")"
        if [[ "${#args[@]}" -lt 2 ]]; then
          xdg-open "${TARGET_DIR}"
        else
          MORE_THAN_ONE="1"
        fi
      done
      if [[ "${MORE_THAN_ONE}" == "1" ]]; then
        xdg-open "${EXTRACT_DIR}/$(basename "${EXTRACT_DIR}")"
      fi
      ;;
    "ark")
      "$tool" --batch -o "$(dirname "${args[0]}")" "${args[@]}"
      ;;
    "engrampa")
      "$tool" -h "${args[@]}"
      ;;
    "file-roller")
      "$tool" -h "${args[@]}"
      ;;
    "gxde-shell-compressor")
      "$tool" -h "${args[@]}"
      ;;
    *)
      log.error "Unsupported tool: $tool"
      exit 1
      ;;
  esac
}


# Function to compress a file with the selected tool
# 压缩文件（修复空格路径和多个文件的问题）
compress_file() {
  local tool="$1"
  shift
  local args=("$@")

  case "$tool" in
    "deepin-compressor")
      "$tool" "${args[@]}" compress
      ;;
    "ark")
      "$tool" --add --dialog "${args[@]}"
      ;;
    "engrampa")
      "$tool" -d "${args[@]}"
      ;;
    "file-roller")
      "$tool" -d "${args[@]}"
      ;;
    "gxde-shell-compressor")
      "$tool" -d "${args[@]}"
      ;;
    *)
      log.error "Unsupported tool: $tool"
      exit 1
      ;;
  esac
}


# Main logic
if [[ "$1" == "-f" ]] || [[ "$1" == "--extract" ]]; then
  tool=$(select_tool "${EXTRACTION_TOOLS[@]}")
  log.info "The selected tool is $tool, now launching it"
  log.info "--------------------------------------------------------------------------"
  extract_file "$tool" "${@:2}"

elif [[ "$1" == "-h" ]] || [[ "$1" == "--extract-here" ]]; then
  tool=$(select_tool "${EXTRACTION_TOOLS[@]}")
  log.info "The selected tool is $tool, now launching it"
  log.info "--------------------------------------------------------------------------"
  extract_here "$tool" "${@:2}"

elif [[ "$1" == "-d" ]] || [[ "$1" == "--compress" ]]; then
  if [[ -z "$2" ]]; then
    log.warn "Missing arguments. Usage: -d <file>"
  fi
  tool=$(select_tool "${COMPRESSION_TOOLS[@]}")
  log.info "The selected tool is $tool, now compressing file"
  log.info "--------------------------------------------------------------------------"
  compress_file "$tool" "${@:2}"

else
  log.warn "No valid option provided. Usage: -f <file> or -h <file> or -d <file> <output_file>."
  tool=$(select_tool "${COMPRESSION_TOOLS[@]}")
  log.info "The selected tool is $tool, now launching it directly without any args."
  "$tool"
fi

