#!/bin/sh
#
# Copyright (c) 2026 neoche contributors
# This program and the accompanying materials are made
# available under the terms of the Eclipse Public License 2.0
# which is available at https://www.eclipse.org/legal/epl-2.0/
#
# SPDX-License-Identifier: EPL-2.0
#

set -e

if ! whoami &> /dev/null; then
  if [ -w /etc/passwd ]; then
    echo "${USER_NAME:-user}:x:$(id -u):0:${USER_NAME:-user} user:${HOME}:/bin/bash" >> /etc/passwd
    echo "${USER_NAME:-user}:x:$(id -u):" >> /etc/group
  fi
fi

ls -la /neovim/

export MACHINE_EXEC_PORT=3333
nohup /neovim/bin/machine-exec --url "127.0.0.1:${MACHINE_EXEC_PORT}" &

ldd_output=$(ldd /bin/ls 2>/dev/null || true)
case "$ldd_output" in
  *musl*)
    echo "[INFO] musl libc detected, using musl binaries"
    NVIM_DIR=/neovim/neovim-linux-musl
    export LD_LIBRARY_PATH="${NVIM_DIR}/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
    ;;
  *)
    echo "[INFO] glibc detected, using libc binaries"
    NVIM_DIR=/neovim/neovim-linux-libc
    ;;
esac

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

if [ -n "$NVIM_DISTRO" ]; then
  /neovim/bootstrap-distro.sh
fi

cd "${PROJECT_SOURCE:-/projects}"

exec /neovim/bin/ttyd -W -p 7681 -t fontSize=14 -t fontFamily="monospace" nvim .
