#!/bin/sh -

opts='-T 0'
(ls $opts  2>&1) > /dev/null || opts=
copts='--color=tty'
xopts='--color=no'
(ls $xopts 2>&1) > /dev/null || { copts=; xopts=; }
config=${COLORRC-$HOME/etc/colorrc}

# setenvls - output code to set GNU ls environment variables
# Steve Kinzler, steve@kinzler.com, Mar 98/Dec 03/Aug 22
# https://kinzler.com/me/home.html#unixcfg

case "$SHELL" in
*csh)	dcarg=-c;;
*)	dcarg=-b;;
esac
pcfg=; bad=

while :
do
	case $# in
	0)	break;;
	*)	case "$1" in
		-[asbkz])	dcarg=-b;;
		-[ct])		dcarg=-c;;
		-p)		pcfg=t;;

		--)		shift; break;;
		-h)		bad=t; break;;
		-*)		bad=t; echo "$0: unknown option ($1)" 1>&2;;
		*)		break;;
		esac
		shift;;
	esac
done

case "$#" in
0)	;;
1)	config="$1";;
*)	bad=t;;
esac

case "$bad" in
?*)	cat << EOF 1>&2
usage: $0 [ -b | -c ] [ -p ] [ file ]
	-b	output Bourne shell code
	-c	output C shell code
	-p	print configuration
EOF
	exit 1;;
esac

tmp="${TMPDIR:-/tmp}"/selc$$
config2="${TMPDIR:-/tmp}"/selcC$$
config3="${TMPDIR:-/tmp}"/selcD$$
trap "rm -f '$tmp' '$config2' '$config3'; exit" 0 1 2 13 15

test -s "$config" && sed -n 's/^#2#//p' < "$config" > "$config2"
test -s "$config" && sed -n 's/^#3#//p' < "$config" > "$config3"

case "$pcfg" in
?*)	if test -s "$config"
	then	cat < "$config"
	else	(dircolors -p) 2> /dev/null
	fi
	test -s "$config2" && cat < "$config2"
	test -s "$config3" && cat < "$config3"
	exit 0;;
esac

LS_OPTIONS=; LS_COLORS=; export LS_OPTIONS LS_COLORS

if test -s "$config"
then	dircolors $dcarg "$config"
else	dircolors $dcarg
fi > "$tmp" 2> /dev/null

case `grep 'LS_COLORS.*:' "$tmp"` in
?*)	opts="$copts $opts";;
*)	opts="$xopts $opts"
	test -s "$tmp" || opts=;;
esac
opts=`echo "$opts" | sed 's/^ *//; s/ *$//'`

case "$dcarg" in
-c)	echo 'set noglob;';;
esac

grep LS_COLORS "$tmp"; echo \;
if test -s "$config2"
then	dircolors $dcarg "$config2" > "$tmp" 2> /dev/null
	sed -n 's/LS_COLORS/&2/p' "$tmp"; echo \;
fi
if test -s "$config3"
then	dircolors $dcarg "$config3" > "$tmp" 2> /dev/null
	sed -n 's/LS_COLORS/&3/p' "$tmp"; echo \;
fi

case "$dcarg" in
-c)	echo "setenv LS_OPTIONS '$opts';";;
*)	echo "LS_OPTIONS='$opts';" \
	     'export LS_COLORS LS_COLORS2 LS_COLORS3 LS_OPTIONS;';;
esac

case "$dcarg" in	# for FreeBSD/MacOS ls(1); does if tty and colorterm
-c)	echo 'setenv CLICOLOR;';;
*)	echo 'CLICOLOR=; export CLICOLOR;';;
esac

sed -n 's/^#INCLUDE#[ 	]*//p' "$config" |
case "$dcarg" in
-c)	sed 's/^/setenv /; s/=/ /; s/$/;/';;
*)	sed 's/^/export /; s/$/;/';;
esac

case "$dcarg" in
-c)	echo 'unset noglob;';;
esac

# exit false if dircolors was not available for this run
test -n "`which dircolors 2> /dev/null`"
