#!/usr/bin/env bash

MODULE_GRUB_THEME_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MODULE_GRUB_THEME_PROJECT_ROOT="$(cd "$MODULE_GRUB_THEME_DIR/../../.." && pwd)"

# shellcheck source=lib/package.sh
source "$MODULE_GRUB_THEME_PROJECT_ROOT/lib/package.sh"
# shellcheck source=modules/boot/grub-theme/config.sh
source "$MODULE_GRUB_THEME_DIR/config.sh"
# shellcheck source=modules/boot/grub-theme/metadata.conf
source "$MODULE_GRUB_THEME_DIR/metadata.conf"

module_grub_theme_metadata() {
  printf '%s|%s|%s\n' "$MODULE_ID" "$MODULE_NAME" "$MODULE_DESCRIPTION"
}

module_grub_theme_archive_dir() {
  if [[ -d "$MODULE_GRUB_THEME_PROJECT_ROOT/$POSTINSTALL_GRUB_THEME_ARCHIVE_DIR_PRIMARY" ]]; then
    printf '%s\n' "$MODULE_GRUB_THEME_PROJECT_ROOT/$POSTINSTALL_GRUB_THEME_ARCHIVE_DIR_PRIMARY"
  else
    printf '%s\n' "$MODULE_GRUB_THEME_PROJECT_ROOT/$POSTINSTALL_GRUB_THEME_ARCHIVE_DIR_FALLBACK"
  fi
}

module_grub_theme_list_archives() {
  local archive_dir=""
  archive_dir="$(module_grub_theme_archive_dir)"
  find "$archive_dir" -maxdepth 1 -type f \( -name '*.zip' -o -name '*.tar.gz' -o -name '*.tgz' \) -printf '%f\n' | sort
}

module_grub_theme_extract() {
  local archive_name="$1"
  local archive_dir=""
  local archive_path=""
  local target_dir=""

  archive_dir="$(module_grub_theme_archive_dir)"
  archive_path="$archive_dir/$archive_name"
  target_dir="$POSTINSTALL_GRUB_THEME_INSTALL_DIR/${archive_name%.*}"

  mkdir -p "$target_dir"

  case "$archive_name" in
    *.zip)
      if ! package_is_installed unzip; then
        package_refresh_indexes
        package_install unzip
      fi
      unzip -o "$archive_path" -d "$target_dir" >/dev/null
      ;;
    *.tar.gz|*.tgz)
      tar -xzf "$archive_path" -C "$target_dir"
      ;;
    *)
      ui_error "Archive de theme non supportee : $archive_name"
      return 1
      ;;
  esac

  find "$target_dir" -type f -name 'theme.txt' | head -n 1
}

module_grub_theme_install() {
  local archive_name="$1"
  local theme_path=""

  if [[ -z "$archive_name" ]]; then
    ui_error "Aucune archive de theme specifiee"
    return 1
  fi

  mkdir -p /etc/default/grub.d
  theme_path="$(module_grub_theme_extract "$archive_name")" || return 1

  printf 'GRUB_THEME="%s"\n' "$theme_path" > "$POSTINSTALL_GRUB_THEME_CONFIG_FILE"
  update-grub

  log_info "Theme GRUB configure : $archive_name"
  ui_success "Theme GRUB configure : $archive_name"
}

module_grub_theme_test() {
  test -f "$POSTINSTALL_GRUB_THEME_CONFIG_FILE" || return 1
  grep -q '^GRUB_THEME=' "$POSTINSTALL_GRUB_THEME_CONFIG_FILE" || return 1
}
