#!/usr/bin/env bash
# =============================================================================
#  Vastra — Linux installer  (command-line)
# -----------------------------------------------------------------------------
#  Builds a native Vastra AppImage on THIS Linux machine and installs it into
#  your user account (no sudo needed): binary in ~/.local/share/vastra, a
#  `vastra` command in ~/.local/bin, and an app-menu entry.
#
#  Why build here?  A Linux binary (.AppImage / .deb) can only be produced on
#  Linux — it needs appimagetool / fpm which don't exist on Windows. So this
#  script does the (fast) build on your machine, then installs the result.
#
#  Usage:
#     # from inside the Vastra source folder:
#     bash install-vastra-linux.sh
#
#     # or point it at the source you copied over:
#     VASTRA_SRC=/path/to/vastra_browser bash install-vastra-linux.sh
#
#     # or let it git-clone (set the repo first):
#     VASTRA_REPO=https://github.com/you/vastra.git bash install-vastra-linux.sh
# =============================================================================
set -euo pipefail

# ---- pretty output ----------------------------------------------------------
c_orange='\033[38;5;208m'; c_dim='\033[2m'; c_red='\033[31m'; c_grn='\033[32m'; c_rst='\033[0m'
say()  { printf "${c_orange}▸${c_rst} %s\n" "$*"; }
ok()   { printf "${c_grn}✓${c_rst} %s\n" "$*"; }
warn() { printf "${c_red}!${c_rst} %s\n" "$*"; }
die()  { printf "${c_red}✗ %s${c_rst}\n" "$*" >&2; exit 1; }

cat <<'BANNER'
        __     __        _
        \ \   / /_ _ ___| |_ _ __ __ _
         \ \ / / _` / __| __| '__/ _` |
          \ V / (_| \__ \ |_| | | (_| |
           \_/ \__,_|___/\__|_|  \__,_|   Linux installer
BANNER

APP_NAME="Vastra"
PKG_NAME="vastra"
INSTALL_DIR="${HOME}/.local/share/vastra"
BIN_DIR="${HOME}/.local/bin"
DESKTOP_DIR="${HOME}/.local/share/applications"
ICON_DIR="${HOME}/.local/share/icons/hicolor/512x512/apps"

# ---- 1. prerequisites -------------------------------------------------------
say "Checking prerequisites…"
command -v node >/dev/null 2>&1 || die "Node.js is required (v18+). Install it: https://nodejs.org"
command -v npm  >/dev/null 2>&1 || die "npm is required (comes with Node.js)."
NODE_MAJOR="$(node -p 'process.versions.node.split(".")[0]')"
[ "${NODE_MAJOR}" -ge 18 ] || die "Node.js 18+ required (found $(node -v))."
ok "Node $(node -v), npm $(npm -v)"

# ---- 2. locate the Vastra source -------------------------------------------
SRC=""
if [ -n "${VASTRA_SRC:-}" ] && [ -f "${VASTRA_SRC}/package.json" ]; then
  SRC="${VASTRA_SRC}"
elif [ -f "./package.json" ] && grep -q '"vastra-browser"' ./package.json 2>/dev/null; then
  SRC="$(pwd)"
elif [ -f "../package.json" ] && grep -q '"vastra-browser"' ../package.json 2>/dev/null; then
  SRC="$(cd .. && pwd)"
elif [ -n "${VASTRA_REPO:-}" ]; then
  command -v git >/dev/null 2>&1 || die "git is required to clone. Install git or set VASTRA_SRC."
  SRC="$(mktemp -d)/vastra"
  say "Cloning ${VASTRA_REPO}…"
  git clone --depth 1 "${VASTRA_REPO}" "${SRC}"
else
  die "Couldn't find Vastra source. Run this inside the vastra_browser folder, or set VASTRA_SRC=/path or VASTRA_REPO=git-url."
fi
ok "Source: ${SRC}"

# ---- 3. build the AppImage --------------------------------------------------
cd "${SRC}"
say "Installing dependencies (this may take a minute)…"
if [ -f package-lock.json ]; then npm ci --no-audit --no-fund; else npm install --no-audit --no-fund; fi

say "Building the renderer…"
npm run build

say "Packaging the Linux AppImage…"
# CSC off → unsigned (fine for personal use)
export CSC_IDENTITY_AUTO_DISCOVERY=false
npx electron-builder --linux AppImage --x64

APPIMAGE="$(ls -1 dist-installer/*.AppImage 2>/dev/null | head -n1 || true)"
[ -n "${APPIMAGE}" ] || die "Build finished but no .AppImage was produced in dist-installer/."
ok "Built: ${APPIMAGE}"

# ---- 4. install into the user account --------------------------------------
say "Installing ${APP_NAME}…"
mkdir -p "${INSTALL_DIR}" "${BIN_DIR}" "${DESKTOP_DIR}" "${ICON_DIR}"

cp -f "${APPIMAGE}" "${INSTALL_DIR}/Vastra.AppImage"
chmod +x "${INSTALL_DIR}/Vastra.AppImage"

# `vastra` launcher on PATH
ln -sf "${INSTALL_DIR}/Vastra.AppImage" "${BIN_DIR}/vastra"

# icon
if [ -f "build/icon.png" ]; then
  cp -f "build/icon.png" "${ICON_DIR}/vastra.png"
fi

# desktop entry
cat > "${DESKTOP_DIR}/vastra.desktop" <<DESKTOP
[Desktop Entry]
Type=Application
Name=Vastra
GenericName=Web Browser
Comment=Browse beyond — a calm, productivity-first browser
Exec=${INSTALL_DIR}/Vastra.AppImage %U
Icon=vastra
Terminal=false
Categories=Network;WebBrowser;
MimeType=text/html;text/xml;application/xhtml+xml;x-scheme-handler/http;x-scheme-handler/https;
StartupNotify=true
StartupWMClass=Vastra
DESKTOP
chmod +x "${DESKTOP_DIR}/vastra.desktop" || true

# refresh menus (best effort)
command -v update-desktop-database >/dev/null 2>&1 && update-desktop-database "${DESKTOP_DIR}" >/dev/null 2>&1 || true

echo
ok "${APP_NAME} installed!"
echo -e "${c_dim}  • Launch from your app menu, or run:  ${c_rst}vastra"
echo -e "${c_dim}  • Binary:    ${INSTALL_DIR}/Vastra.AppImage${c_rst}"
echo -e "${c_dim}  • Uninstall: bash ${INSTALL_DIR}/uninstall.sh${c_rst}"

# ---- 5. drop an uninstaller -------------------------------------------------
cat > "${INSTALL_DIR}/uninstall.sh" <<UNINSTALL
#!/usr/bin/env bash
set -e
echo "Removing Vastra…"
rm -f "${BIN_DIR}/vastra"
rm -f "${DESKTOP_DIR}/vastra.desktop"
rm -f "${ICON_DIR}/vastra.png"
rm -rf "${INSTALL_DIR}"
command -v update-desktop-database >/dev/null 2>&1 && update-desktop-database "${DESKTOP_DIR}" >/dev/null 2>&1 || true
echo "Vastra removed. (Your settings in ~/.config/vastra-browser were kept.)"
UNINSTALL
chmod +x "${INSTALL_DIR}/uninstall.sh"

# PATH hint
case ":${PATH}:" in
  *":${BIN_DIR}:"*) : ;;
  *) warn "Add ~/.local/bin to your PATH to use the 'vastra' command:";
     echo -e "${c_dim}    echo 'export PATH=\"\$HOME/.local/bin:\$PATH\"' >> ~/.bashrc && source ~/.bashrc${c_rst}" ;;
esac
