#!/usr/bin/env bash

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

# shellcheck source=lib/package.sh
source "$MODULE_BITWARDEN_PROJECT_ROOT/lib/package.sh"
# shellcheck source=lib/system.sh
source "$MODULE_BITWARDEN_PROJECT_ROOT/lib/system.sh"
# shellcheck source=modules/passwords/bitwarden/config.sh
source "$MODULE_BITWARDEN_DIR/config.sh"
# shellcheck source=modules/passwords/bitwarden/metadata.conf
source "$MODULE_BITWARDEN_DIR/metadata.conf"

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

module_bitwarden_config_path() {
  printf '%s/%s\n' "$MODULE_BITWARDEN_PROJECT_ROOT" "$POSTINSTALL_BITWARDEN_SETTINGS_FILE"
}

module_bitwarden_settings() {
  local config_path=""
  local server_url="$POSTINSTALL_BITWARDEN_SERVER_URL"
  local email="$POSTINSTALL_BITWARDEN_EMAIL"
  local target_user="$POSTINSTALL_BITWARDEN_TARGET_USER"
  local install_cli="$POSTINSTALL_BITWARDEN_INSTALL_CLI"
  local install_desktop="$POSTINSTALL_BITWARDEN_INSTALL_DESKTOP"
  local install_firefox_extension="$POSTINSTALL_BITWARDEN_INSTALL_FIREFOX_EXTENSION"
  local install_chromium_extension="$POSTINSTALL_BITWARDEN_INSTALL_CHROMIUM_EXTENSION"
  local install_google_chrome_extension="$POSTINSTALL_BITWARDEN_INSTALL_GOOGLE_CHROME_EXTENSION"
  local login_cli_now="$POSTINSTALL_BITWARDEN_LOGIN_CLI_NOW"
  local uri_match_detection="$POSTINSTALL_BITWARDEN_URI_MATCH_DETECTION"

  config_path="$(module_bitwarden_config_path)"
  if [[ -f "$config_path" ]]; then
    while IFS='=' read -r key value; do
      case "$key" in
        server_url) server_url="$value" ;;
        email) email="$value" ;;
        target_user) target_user="$value" ;;
        install_cli) install_cli="$value" ;;
        install_desktop) install_desktop="$value" ;;
        install_firefox_extension) install_firefox_extension="$value" ;;
        install_chromium_extension) install_chromium_extension="$value" ;;
        install_google_chrome_extension) install_google_chrome_extension="$value" ;;
        login_cli_now) login_cli_now="$value" ;;
        uri_match_detection) uri_match_detection="$value" ;;
      esac
    done < <(
      awk '
        /^[[:space:]]*server_url:/ { print "server_url=" $2 }
        /^[[:space:]]*email:/ { print "email=" $2 }
        /^[[:space:]]*target_user:/ { print "target_user=" $2 }
        /^[[:space:]]*install_cli:/ { print "install_cli=" $2 }
        /^[[:space:]]*install_desktop:/ { print "install_desktop=" $2 }
        /^[[:space:]]*install_firefox_extension:/ { print "install_firefox_extension=" $2 }
        /^[[:space:]]*install_chromium_extension:/ { print "install_chromium_extension=" $2 }
        /^[[:space:]]*install_google_chrome_extension:/ { print "install_google_chrome_extension=" $2 }
        /^[[:space:]]*login_cli_now:/ { print "login_cli_now=" $2 }
        /^[[:space:]]*uri_match_detection:/ { print "uri_match_detection=" $2 }
      ' "$config_path"
    )
  fi

  printf '%s|%s|%s|%s|%s|%s|%s|%s|%s|%s\n' \
    "$server_url" \
    "$email" \
    "$target_user" \
    "$install_cli" \
    "$install_desktop" \
    "$install_firefox_extension" \
    "$install_chromium_extension" \
    "$install_google_chrome_extension" \
    "$login_cli_now" \
    "$uri_match_detection"
}

module_bitwarden_string_to_bool() {
  case "$1" in
    true|yes|y|1|on) printf 'true\n' ;;
    *) printf 'false\n' ;;
  esac
}

module_bitwarden_require_directory() {
  install -d -m 0755 "$1"
}

module_bitwarden_user_home() {
  local target_user="$1"

  getent passwd "$target_user" | cut -d: -f6
}

module_bitwarden_run_as_user() {
  local target_user="$1"
  shift
  local target_home=""

  if ! system_user_exists "$target_user"; then
    ui_error "Utilisateur Bitwarden introuvable : $target_user"
    return 1
  fi

  target_home="$(module_bitwarden_user_home "$target_user")"
  if [[ -z "$target_home" ]]; then
    ui_error "Impossible de determiner le HOME de $target_user"
    return 1
  fi

  if [[ "${EUID:-$(id -u)}" -eq 0 ]]; then
    runuser -u "$target_user" -- env HOME="$target_home" XDG_CONFIG_HOME="$target_home/.config" "$@"
  else
    HOME="$target_home" XDG_CONFIG_HOME="$target_home/.config" "$@"
  fi
}

module_bitwarden_download() {
  local url="$1"
  local destination="$2"

  curl -fsSL "$url" -o "$destination"
}

module_bitwarden_install_cli() {
  local temp_dir=""
  local archive_path=""

  if command -v bw >/dev/null 2>&1; then
    ui_info "Bitwarden CLI deja installe"
    return 0
  fi

  temp_dir="$(mktemp -d)"
  archive_path="$temp_dir/bitwarden-cli.zip"

  package_refresh_indexes
  package_install curl unzip ca-certificates
  module_bitwarden_download "$POSTINSTALL_BITWARDEN_CLI_DOWNLOAD_URL" "$archive_path"
  unzip -o "$archive_path" -d "$temp_dir" >/dev/null

  if [[ ! -f "$temp_dir/bw" ]]; then
    ui_error "Binaire Bitwarden CLI introuvable apres extraction"
    rm -rf "$temp_dir"
    return 1
  fi

  install -m 0755 "$temp_dir/bw" /usr/local/bin/bw
  rm -rf "$temp_dir"

  ui_success "Bitwarden CLI installe"
}

module_bitwarden_install_desktop() {
  local target_user="$1"
  local temp_dir=""
  local appimage_path=""
  local install_path="/opt/bitwarden/Bitwarden.AppImage"

  temp_dir="$(mktemp -d)"
  appimage_path="$temp_dir/Bitwarden.AppImage"

  package_refresh_indexes
  package_install curl ca-certificates
  module_bitwarden_download "$POSTINSTALL_BITWARDEN_DESKTOP_DOWNLOAD_URL" "$appimage_path"

  if [[ ! -s "$appimage_path" ]]; then
    ui_error "Telechargement de l'application Bitwarden echoue"
    rm -rf "$temp_dir"
    return 1
  fi

  module_bitwarden_require_directory /opt/bitwarden
  install -m 0755 "$appimage_path" "$install_path"
  rm -rf "$temp_dir"

  cat > /usr/local/bin/bitwarden-desktop <<'EOF'
#!/usr/bin/env bash
exec /opt/bitwarden/Bitwarden.AppImage "$@"
EOF
  chmod 0755 /usr/local/bin/bitwarden-desktop

  if system_user_exists "$target_user"; then
    module_bitwarden_write_desktop_config "$target_user"
  fi

  ui_success "Application desktop Bitwarden installee"
}

module_bitwarden_write_desktop_config() {
  local target_user="$1"
  local config_dir="/home/$target_user/.config/Bitwarden"
  local config_file="$config_dir/data.json"

  module_bitwarden_require_directory "$config_dir"
  cat > "$config_file" <<EOF
{
  "environmentUrls": {
    "base": "$POSTINSTALL_BITWARDEN_SERVER_URL"
  },
  "configuredByAdmin": true,
  "notes": {
    "uriMatchDetection": "$POSTINSTALL_BITWARDEN_URI_MATCH_DETECTION"
  }
}
EOF
  chown -R "$target_user:$target_user" "$config_dir"
}

module_bitwarden_write_firefox_policy() {
  module_bitwarden_require_directory "$(dirname "$POSTINSTALL_BITWARDEN_FIREFOX_POLICIES_FILE")"
  cat > "$POSTINSTALL_BITWARDEN_FIREFOX_POLICIES_FILE" <<EOF
{
  "policies": {
    "ExtensionSettings": {
      "$POSTINSTALL_BITWARDEN_FIREFOX_EXTENSION_ID": {
        "installation_mode": "force_installed",
        "install_url": "$POSTINSTALL_BITWARDEN_FIREFOX_EXTENSION_URL"
      }
    },
    "3rdparty": {
      "Extensions": {
        "$POSTINSTALL_BITWARDEN_FIREFOX_EXTENSION_ID": {
          "environment": {
            "base": "$POSTINSTALL_BITWARDEN_SERVER_URL"
          }
        }
      }
    }
  }
}
EOF
}

module_bitwarden_write_chromium_policy_file() {
  local policy_file="$1"

  module_bitwarden_require_directory "$(dirname "$policy_file")"
  cat > "$policy_file" <<EOF
{
  "3rdparty": {
    "extensions": {
      "$POSTINSTALL_BITWARDEN_CHROME_EXTENSION_ID": {
        "environment": {
          "base": "$POSTINSTALL_BITWARDEN_SERVER_URL"
        }
      }
    }
  },
  "ExtensionInstallForcelist": [
    "$POSTINSTALL_BITWARDEN_CHROME_EXTENSION_ID;$POSTINSTALL_BITWARDEN_CHROME_EXTENSION_UPDATE_URL"
  ]
}
EOF
}

module_bitwarden_install_browser_package_if_available() {
  local package_name="$1"

  if package_is_installed "$package_name"; then
    return 0
  fi

  if package_is_available "$package_name"; then
    package_refresh_indexes
    package_install "$package_name"
    return 0
  fi

  ui_warn "Paquet indisponible : $package_name"
  return 1
}

module_bitwarden_configure_firefox() {
  module_bitwarden_install_browser_package_if_available firefox-esr || true
  module_bitwarden_write_firefox_policy
  ui_success "Politique Firefox Bitwarden ecrite"
}

module_bitwarden_configure_chromium() {
  module_bitwarden_install_browser_package_if_available chromium || true
  module_bitwarden_write_chromium_policy_file "$POSTINSTALL_BITWARDEN_CHROMIUM_POLICIES_FILE"
  ui_success "Politique Chromium Bitwarden ecrite"
}

module_bitwarden_configure_google_chrome() {
  if package_is_available google-chrome-stable || package_is_installed google-chrome-stable; then
    module_bitwarden_install_browser_package_if_available google-chrome-stable || true
    module_bitwarden_write_chromium_policy_file "$POSTINSTALL_BITWARDEN_CHROME_POLICIES_FILE"
    ui_success "Politique Google Chrome Bitwarden ecrite"
  else
    ui_warn "Google Chrome n'est pas disponible sur cette machine"
  fi
}

module_bitwarden_cli_login() {
  local email="$1"
  local target_user="$2"
  local password=""

  if ! command -v bw >/dev/null 2>&1; then
    ui_warn "CLI Bitwarden absente, connexion ignoree"
    return 0
  fi

  printf 'Mot de passe Bitwarden pour %s : ' "$email"
  read -r -s password
  printf '\n'

  if [[ -z "$password" ]]; then
    ui_warn "Mot de passe vide, connexion CLI ignoree"
    return 0
  fi

  module_bitwarden_run_as_user "$target_user" env BW_PASSWORD="$password" bw login "$email" --passwordenv BW_PASSWORD || return 1
  password=""
  ui_success "Connexion CLI Bitwarden terminee"
}

module_bitwarden_install() {
  local server_url="${1:-}"
  local email="${2:-}"
  local target_user="${3:-}"
  local install_cli="${4:-}"
  local install_desktop="${5:-}"
  local install_firefox_extension="${6:-}"
  local install_chromium_extension="${7:-}"
  local install_google_chrome_extension="${8:-}"
  local login_cli_now="${9:-}"
  local uri_match_detection="${10:-}"
  local settings=""

  if [[ -z "$server_url" ]]; then
    settings="$(module_bitwarden_settings)"
    IFS='|' read -r server_url email target_user install_cli install_desktop install_firefox_extension install_chromium_extension install_google_chrome_extension login_cli_now uri_match_detection <<< "$settings"
  fi

  POSTINSTALL_BITWARDEN_SERVER_URL="$server_url"
  POSTINSTALL_BITWARDEN_EMAIL="$email"
  POSTINSTALL_BITWARDEN_TARGET_USER="$target_user"
  POSTINSTALL_BITWARDEN_INSTALL_CLI="$(module_bitwarden_string_to_bool "$install_cli")"
  POSTINSTALL_BITWARDEN_INSTALL_DESKTOP="$(module_bitwarden_string_to_bool "$install_desktop")"
  POSTINSTALL_BITWARDEN_INSTALL_FIREFOX_EXTENSION="$(module_bitwarden_string_to_bool "$install_firefox_extension")"
  POSTINSTALL_BITWARDEN_INSTALL_CHROMIUM_EXTENSION="$(module_bitwarden_string_to_bool "$install_chromium_extension")"
  POSTINSTALL_BITWARDEN_INSTALL_GOOGLE_CHROME_EXTENSION="$(module_bitwarden_string_to_bool "$install_google_chrome_extension")"
  POSTINSTALL_BITWARDEN_LOGIN_CLI_NOW="$(module_bitwarden_string_to_bool "$login_cli_now")"
  POSTINSTALL_BITWARDEN_URI_MATCH_DETECTION="$uri_match_detection"

  ui_info "Serveur Bitwarden cible : $POSTINSTALL_BITWARDEN_SERVER_URL"
  ui_info "Preference a verifier apres premiere connexion : detection d'URI = $POSTINSTALL_BITWARDEN_URI_MATCH_DETECTION"

  if [[ "$POSTINSTALL_BITWARDEN_INSTALL_CLI" == "true" ]]; then
    module_bitwarden_install_cli || return 1
    module_bitwarden_run_as_user "$target_user" bw config server "$POSTINSTALL_BITWARDEN_SERVER_URL" || return 1
  fi

  if [[ "$POSTINSTALL_BITWARDEN_INSTALL_DESKTOP" == "true" ]]; then
    module_bitwarden_install_desktop "$target_user" || return 1
  fi

  if [[ "$POSTINSTALL_BITWARDEN_INSTALL_FIREFOX_EXTENSION" == "true" ]]; then
    module_bitwarden_configure_firefox || return 1
  fi

  if [[ "$POSTINSTALL_BITWARDEN_INSTALL_CHROMIUM_EXTENSION" == "true" ]]; then
    module_bitwarden_configure_chromium || return 1
  fi

  if [[ "$POSTINSTALL_BITWARDEN_INSTALL_GOOGLE_CHROME_EXTENSION" == "true" ]]; then
    module_bitwarden_configure_google_chrome || return 1
  fi

  if [[ "$POSTINSTALL_BITWARDEN_LOGIN_CLI_NOW" == "true" ]]; then
    module_bitwarden_cli_login "$POSTINSTALL_BITWARDEN_EMAIL" "$target_user" || return 1
  fi

  log_info "Bitwarden configure pour $POSTINSTALL_BITWARDEN_SERVER_URL"
  ui_success "Bitwarden configure"
}

module_bitwarden_test() {
  local ok=0

  if command -v bw >/dev/null 2>&1; then
    ok=1
  fi

  if [[ -f "$POSTINSTALL_BITWARDEN_FIREFOX_POLICIES_FILE" ]]; then
    ok=1
  fi

  if [[ -f "$POSTINSTALL_BITWARDEN_CHROMIUM_POLICIES_FILE" || -f "$POSTINSTALL_BITWARDEN_CHROME_POLICIES_FILE" ]]; then
    ok=1
  fi

  test -f "$(module_bitwarden_config_path)" || return 1
  (( ok == 1 ))
}
