#!/bin/sh

set -eu

if [ "$(id -u)" -ne 0 ]; then
  echo "ERROR: run this script as root." >&2
  exit 1
fi

: "${LBI_ROOT:?ERROR: LBI_ROOT is not set}"

ensure_link() {
  target=$1
  link_path=$2

  if [ -L "$link_path" ]; then
    rm -f "$link_path"
  elif [ -e "$link_path" ]; then
    echo "ERROR: $link_path exists and is not a symlink" >&2
    exit 1
  fi

  ln -s "$target" "$link_path"
}

# Create target-side virtual filesystem paths.
mkdir -p "$LBI_ROOT/system/devices"
mkdir -p "$LBI_ROOT/system/processes"
mkdir -p "$LBI_ROOT/system/system"
mkdir -p "$LBI_ROOT/system/run"
mkdir -p "$LBI_ROOT/system/devices/pts"
mkdir -p "$LBI_ROOT/system/devices/shm"

# Create top-level compatibility links.
ensure_link system/devices "$LBI_ROOT/dev"
ensure_link system/processes "$LBI_ROOT/proc"
ensure_link system/system "$LBI_ROOT/sys"
ensure_link system/run "$LBI_ROOT/run"

# Mount virtual filesystems (LFS-style sequence).
mount -o bind /dev "$LBI_ROOT/dev"
mount -t devpts devpts "$LBI_ROOT/dev/pts" -o gid=5,mode=0620
mount -t proc proc "$LBI_ROOT/proc"
mount -t sysfs sysfs "$LBI_ROOT/sys"
mount -t tmpfs tmpfs "$LBI_ROOT/run"

if [ -h "$LBI_ROOT/dev/shm" ]; then
  install -d -m 1777 "$LBI_ROOT/system/run/shm"
else
  mount -t tmpfs -o nosuid,nodev tmpfs "$LBI_ROOT/dev/shm"
fi

echo "Virtual filesystem link setup and mounts completed for $LBI_ROOT"
