#!/usr/bin/env bash
# MMI Traceability — Linux first-time setup (user install in ~/Program-Traceability)
# Usage:
#   chmod +x linux-first-setup.sh
#   ./linux-first-setup.sh
# Or double-click in the file manager (Run in Terminal).

set -euo pipefail

APP_NAME="MMI Traceability"
INSTALL_DIR="${HOME}/Program-Traceability"
BIN_NAME="mmi"
DEB_URL="${MMI_DEB_URL:-https://download.nanocodelink.com/MMI/mmi_amd64.deb}"
DEB_FILE="${INSTALL_DIR}/mmi_amd64.deb"
DESKTOP_DIR="${HOME}/.local/share/applications"
DESKTOP_FILE="${DESKTOP_DIR}/mmi.desktop"
ICON_CANDIDATES=(
  "${INSTALL_DIR}/extract/usr/share/icons/hicolor/128x128/apps"
  "${INSTALL_DIR}/extract/usr/share/icons/hicolor/256x256/apps"
  "${INSTALL_DIR}/extract/usr/share/pixmaps"
)

log()  { echo -e "\n==> $*"; }
ok()   { echo "    OK: $*"; }
warn() { echo "    WARN: $*"; }
die()  { echo "ERROR: $*" >&2; exit 1; }

need_cmd() {
  command -v "$1" >/dev/null 2>&1 || die "Missing command: $1"
}

ask_yes() {
  local prompt="$1"
  local reply
  read -r -p "${prompt} [Y/n] " reply || true
  case "${reply:-Y}" in
    Y|y|yes|YES|"") return 0 ;;
    *) return 1 ;;
  esac
}

echo "========================================"
echo "  ${APP_NAME} — Linux first-time setup"
echo "========================================"
echo "Install folder: ${INSTALL_DIR}"
echo "Download URL:   ${DEB_URL}"
echo

# --- 0) Remove previous system (apt) install if present ---
mapfile -t existing_pkgs < <(dpkg -l 2>/dev/null | awk '/^ii/ && $2 ~ /^mmi($|:)/ {print $2}')
if ((${#existing_pkgs[@]})); then
  log "Found previous apt/dpkg install: ${existing_pkgs[*]}"
  if ask_yes "Remove system package so auto-update can work from ~/Program-Traceability?"; then
    sudo apt remove -y mmi 2>/dev/null || true
    sudo apt remove -y "${existing_pkgs[@]}" || true
    ok "System packages removed (or already gone)"
  else
    warn "Skipped apt remove — auto-update may fail if binary is under /usr"
  fi
fi

# --- 1) System libraries ---
log "Installing system libraries (needs sudo password once)"
need_cmd sudo
need_cmd apt-get
sudo apt-get update

WEBKIT_PKG="libwebkit2gtk-4.1-0"
if ! apt-cache show libwebkit2gtk-4.1-0 >/dev/null 2>&1; then
  WEBKIT_PKG="libwebkit2gtk-4.0-37"
fi

sudo DEBIAN_FRONTEND=noninteractive apt-get install -y \
  "${WEBKIT_PKG}" \
  libgtk-3-0 \
  libayatana-appindicator3-1 \
  librsvg2-2 \
  libgbm1 \
  libegl1 \
  libusb-1.0-0 \
  libudev1 \
  ca-certificates \
  xdg-utils \
  wget \
  binutils
ok "System libraries installed"

# --- 2) Download .deb ---
log "Preparing ${INSTALL_DIR}"
mkdir -p "${INSTALL_DIR}"
cd "${INSTALL_DIR}"

log "Downloading ${DEB_URL}"
need_cmd wget
wget -O "${DEB_FILE}" "${DEB_URL}" || die "Download failed. Check network / URL."
ok "Downloaded $(du -h "${DEB_FILE}" | awk '{print $1}')"

# --- 3) Extract into ~/Program-Traceability (do NOT apt install) ---
log "Extracting .deb into ${INSTALL_DIR} (no sudo apt install)"
rm -rf "${INSTALL_DIR}/extract"
mkdir -p "${INSTALL_DIR}/extract"
if command -v dpkg-deb >/dev/null 2>&1; then
  dpkg-deb -x "${DEB_FILE}" "${INSTALL_DIR}/extract"
else
  (
    cd "${INSTALL_DIR}/extract"
    ar x "${DEB_FILE}"
    if [[ -f data.tar.xz ]]; then tar -xJf data.tar.xz
    elif [[ -f data.tar.gz ]]; then tar -xzf data.tar.gz
    elif [[ -f data.tar.zst ]]; then tar --zstd -xf data.tar.zst
    elif [[ -f data.tar.bz2 ]]; then tar -xjf data.tar.bz2
    else die "Could not extract .deb (need dpkg-deb or ar+tar)"
    fi
  )
fi

SRC=""
for candidate in \
  "${INSTALL_DIR}/extract/usr/bin/mmi" \
  "${INSTALL_DIR}/extract/usr/bin/MMI" \
  "${INSTALL_DIR}/extract/usr/local/bin/mmi"
do
  if [[ -f "${candidate}" ]]; then
    SRC="${candidate}"
    break
  fi
done

if [[ -z "${SRC}" ]]; then
  SRC="$(find "${INSTALL_DIR}/extract" -type f \( -name mmi -o -name MMI \) 2>/dev/null | head -n 1 || true)"
fi

[[ -n "${SRC}" && -f "${SRC}" ]] || die "Binary not found inside .deb. Inspect: find ${INSTALL_DIR}/extract -type f | head"

cp -f "${SRC}" "${INSTALL_DIR}/${BIN_NAME}"
chmod +x "${INSTALL_DIR}/${BIN_NAME}"
ok "Installed ${INSTALL_DIR}/${BIN_NAME}"

# Optional icon for desktop entry
ICON_PATH=""
for dir in "${ICON_CANDIDATES[@]}"; do
  if [[ -d "${dir}" ]]; then
    ICON_PATH="$(find "${dir}" -type f \( -name '*.png' -o -name '*.svg' \) 2>/dev/null | head -n 1 || true)"
    [[ -n "${ICON_PATH}" ]] && break
  fi
done

# Clean extract + deb (keep binary)
rm -rf "${INSTALL_DIR}/extract"
rm -f "${DEB_FILE}"

# --- 4) Desktop / menu shortcut ---
log "Creating application menu shortcut"
mkdir -p "${DESKTOP_DIR}"
cat > "${DESKTOP_FILE}" <<EOF
[Desktop Entry]
Type=Application
Name=${APP_NAME}
Comment=Manufacturing batch traceability
Exec=${INSTALL_DIR}/${BIN_NAME}
Path=${INSTALL_DIR}
Terminal=false
Categories=Utility;
StartupNotify=true
EOF
if [[ -n "${ICON_PATH}" && -f "${ICON_PATH}" ]]; then
  ICON_DEST="${INSTALL_DIR}/icon.png"
  if [[ "${ICON_PATH}" == *.svg ]]; then
    ICON_DEST="${INSTALL_DIR}/icon.svg"
  fi
  cp -f "${ICON_PATH}" "${ICON_DEST}" 2>/dev/null || true
  if [[ -f "${ICON_DEST}" ]]; then
    echo "Icon=${ICON_DEST}" >> "${DESKTOP_FILE}"
  fi
fi
chmod +x "${DESKTOP_FILE}"

if [[ -d "${HOME}/Desktop" ]]; then
  cp -f "${DESKTOP_FILE}" "${HOME}/Desktop/mmi.desktop"
  chmod +x "${HOME}/Desktop/mmi.desktop"
  if command -v gio >/dev/null 2>&1; then
    gio set "${HOME}/Desktop/mmi.desktop" metadata::trusted true 2>/dev/null || true
  fi
  ok "Desktop shortcut: ~/Desktop/mmi.desktop"
fi
ok "Menu shortcut: ${DESKTOP_FILE}"

# --- 5) Done ---
echo
echo "========================================"
echo "  Setup finished"
echo "========================================"
echo "Run with:"
echo "  ${INSTALL_DIR}/${BIN_NAME}"
echo
echo "Or open \"${APP_NAME}\" from the app menu / Desktop."
echo
echo "Map the Windows share (smb://...) with linux-map-share.sh so the app"
echo "can copy Configuration from the shared folder when it starts."
echo
echo "Do NOT use: sudo apt install ./mmi_amd64.deb"
echo "That breaks in-app auto-update."
echo

if ask_yes "Launch ${APP_NAME} now?"; then
  nohup "${INSTALL_DIR}/${BIN_NAME}" >/dev/null 2>&1 &
  ok "Started ${APP_NAME}"
fi
