#!/usr/bin/env bash
source <(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/misc/build.func)
# Copyright (c) 2021-2026 community-scripts ORG
# Author: MickLesk (CanbiZ)
# License: MIT | https://github.com/community-scripts/ProxmoxVE/raw/main/LICENSE
# Source: https://www.meilisearch.com/ | Github: https://github.com/meilisearch/meilisearch

APP="Meilisearch"
var_tags="${var_tags:-full-text-search}"
var_cpu="${var_cpu:-2}"
var_ram="${var_ram:-4096}"
var_disk="${var_disk:-7}"
var_os="${var_os:-debian}"
var_version="${var_version:-13}"
var_arm64="${var_arm64:-no}"
var_unprivileged="${var_unprivileged:-1}"

header_info "$APP"
variables
color
catch_errors

function update_script() {
  header_info
  check_container_storage
  check_container_resources

  setup_meilisearch

  if [[ -d /opt/meilisearch-ui ]]; then
    if check_for_gh_release "meilisearch-ui" "riccox/meilisearch-ui"; then
      msg_info "Stopping Meilisearch-UI"
      systemctl stop meilisearch-ui
      msg_ok "Stopped Meilisearch-UI"

      cp /opt/meilisearch-ui/.env.local /tmp/.env.local.bak
      rm -rf /opt/meilisearch-ui
      fetch_and_deploy_gh_release "meilisearch-ui" "riccox/meilisearch-ui" "tarball"

      msg_info "Configuring Meilisearch-UI"
      cd /opt/meilisearch-ui
      sed -i 's|const hash = execSync("git rev-parse HEAD").toString().trim();|const hash = "unknown";|' /opt/meilisearch-ui/vite.config.ts
      mv /tmp/.env.local.bak /opt/meilisearch-ui/.env.local
      $STD pnpm install
      msg_ok "Configured Meilisearch-UI"

      msg_info "Starting Meilisearch-UI"
      systemctl start meilisearch-ui
      msg_ok "Started Meilisearch-UI"
    fi
  fi

  msg_ok "Updated successfully!"
  exit
}

start
build_container
description

msg_ok "Completed successfully!\n"
echo -e "${CREATING}${GN}${APP} setup has been successfully initialized!${CL}"
echo -e "${INFO}${YW} Access it using the following URL:${CL}"
echo -e "${TAB}${GATEWAY}${BGN}meilisearch: http://${IP}:7700$ | meilisearch-ui: http://${IP}:24900${CL}"
