#!/bin/sh
#Copyright: 2026 Aitor <aitor@genuen.org>
#License: CC0-1.0
#Comment: oneshot; invoke with: sv once x11-common
#Comment: X11/ICE socket dirs only — no mountnfs dep (that blocked DELAYLOGIN)

exec 2>&1

ebegin() { [ "${VERBOSE:-}" = no ] || echo "$@"; }
eend() { r=${1:-0}; shift || true; [ "$r" -eq 0 ] || [ "${VERBOSE:-}" = no ] || echo "$*" >&2; return "$r"; }
einfo() { [ "${VERBOSE:-}" = no ] || echo "$@"; }
ewarn() { echo "$@" >&2; }
eerror() { echo "$@" >&2; }

# /tmp is available after mountall; do not pull mountnfs-bootclean here.
# That chain could hang/delay and, with rmnologin later in boot-run/05,
# leave /run/nologin in place → console login refused.

[ -f /etc/default/rcS ] && . /etc/default/rcS
SOCKET_DIR=.X11-unix
ICE_DIR=.ICE-unix
do_restorecon () {
  if command -v restorecon >/dev/null 2>&1; then
    restorecon "$1"
  fi
}
set_up_dir () {
  DIR="/tmp/$1"
  [ "$VERBOSE" != no ] && einfo "$DIR"
  if [ -e $DIR ] && ! [ -d $DIR ] || [ -h $DIR ]; then
    mv "$DIR" "$(mktemp -d $DIR.XXXXXX)"
  fi
  error=0
  while :; do
    if [ $error -ne 0 ] ; then
      if [ $error -gt 5 ]; then
        eerror "failed to set up $DIR"
        return 1
      fi
      fn="$(mktemp /tmp/testwriteable.XXXXXXXXXX)" || return 1
      rm "$fn"
    fi
    mkdir -p -m 01777 "$DIR" || { rm "$DIR" || error=$((error + 1)) ; continue ; }
    case "$(LC_ALL=C stat -c '%u %g %a %F' "$DIR")" in
      "0 0 1777 directory") break ;;
      "0 0 "*" directory") chmod 01777 "$DIR"; break ;;
      *" directory") chown -h root:root "$DIR" || error=$((error + 1)); continue ;;
      *) eerror "failed to set up $DIR"; return 1 ;;
    esac
  done
  do_restorecon "$DIR"
  return 0
}
ebegin "Setting up X socket directories"
set_up_dir "$SOCKET_DIR" || true
set_up_dir "$ICE_DIR" || true
eend 0
exit 0
