#!/bin/sh

set -e

export USER_ID=$(id -u)
export GROUP_ID=$(id -g)

ldd_output=$(ldd /bin/ls 2>/dev/null || true)
case "$ldd_output" in
  *musl*)
    NVIM_DIR=/neovim-linux-musl
    export LD_LIBRARY_PATH="${NVIM_DIR}/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
    ;;
  *)
    NVIM_DIR=/neovim-linux-libc
    ;;
esac

export PATH="${NVIM_DIR}/bin:${PATH}"
export TERM=xterm-256color

if [ -n "$NVIM_DISTRO" ] && [ ! -d "$HOME/.config/nvim" ]; then
  /bootstrap-distro.sh
fi

if [ -d "$HOME/.config/nvim" ]; then
  echo "[INFO] running headless plugin sync"
  "${NVIM_DIR}/bin/nvim" --headless "+Lazy! sync" +qa 2>&1 || echo "[WARN] plugin sync failed"
  echo "[INFO] plugin sync done"
fi

WORKDIR="${PROJECT_SOURCE:-/projects}"
mkdir -p "$WORKDIR"
cd "$WORKDIR"

TTYD_OPTS="-W -p 7681 -t fontSize=14"
if [ -f /neovim-index.html ]; then
  TTYD_OPTS="$TTYD_OPTS -I /neovim-index.html -t fontFamily='JetBrainsMono NF Mono, monospace'"
else
  TTYD_OPTS="$TTYD_OPTS -t fontFamily=monospace"
fi

NEOCHE_SHELL="${NEOCHE_SHELL:-}"
if [ -n "$NEOCHE_SHELL" ] && command -v "$NEOCHE_SHELL" > /dev/null 2>&1; then
  eval exec /neovim-bin/ttyd $TTYD_OPTS "$NEOCHE_SHELL" -c \"nvim .\"
else
  eval exec /neovim-bin/ttyd $TTYD_OPTS nvim .
fi
