#! /usr/bin/env xs

# Other shells litter the environment with globals that mirror results
# better obtained elsewhere. Clobber the most problematic ones, here:
PWD =
OLDPWD =

# Load user scripts.
if {~ $fn-%safe-wild ()} {
	throw error \~/.xsrc \
		'No %safe-wild (see ~/.xslib.d/*); ~/.xsrc.d/* is not loaded.'
} else {
	catch {|e|
		# This is explained in ~/.xsrc :
		echo $e
		echo '~/.xsin: Spawning rescue shell'
		xs -p
	} {
		%safe-wild '~/.xsuser.d/*.xs' {|exp|
			for f $exp {. $f}
		}
	}
}

# Run the appropriate interactive setup.
if {~ `tty *tty1} {
	# Start an Xorg session.
	startwm
} else {
	# We have a vt or pty session; configure the keyboard.
	stty start undef stop undef
	# Report system status.
	%is-login && {
		.as; echo; pal -r 1 -c 0|%strip-csi; cookie; .an; echo
		if {~ `tty /dev/tty*} {
			on; net; addr; thermal; battery; load; mem; pers; echo
		}
		.ab; where; .an
	}
	# Whine if the history file grows too large.
	# Do this no more than once per hour.
	if {{!~ $history ()} && {~ `{cat $history|wc -l} [5-9]??? *?????}} {
		let ( \
		nf = ~/.local/share/histclean.notified; \
		now = `{date +%s}; \
		ts) {
			ts = `{ls -l --time-style=+%s $nf >[2]/dev/null \
				|cut -d' ' -f6}; \
			if {$now :gt `($ts+3600)} {
				echo 'Consider histclean'
				touch $nf
			}
		}
	}
	# Announce new location when logging in from a different host.
	if {{~ $SSH_TTY ()} && {!~ $SSH_CONNECTION ()} && {!~ $DISPLAY ()}} {
		where
	}
	# Load ./.xspath, if present.
	.load_xspath
	# Override the configured prompt with a randomly-chosen prompt.
	.init_random_prompt
	# Mark persistent
	prompt <={%argify `{det -p}}
}

~ $NIX_PATH () || {clear; name nix; psi}
true
