#!/bin/sh
# usage:
# args are directory names (only 1 allowed). if doesn't end in .d .d is appended.
# first update filename dir.order, fails if any new ones added.
# if first arg. -l list print dir.order else cat
arg=;dir=$1
if test "$(= "$dir"|cut -c 1)" = '-';then
arg=$dir;dir=$2;fi
test "$(= "$dir"|rcut -c1-2)" = '.d'||dir=${dir}.d
test -d "$dir"||{ = "does not exist" >/dev/stderr;exit 1;}
test -e "$dir"/dir.order&&e=x||e=
find "$dir" -mindepth 1 -maxdepth 1 \( -type f -o -type l \) \( ! -iname dir.order\* \) -printf '%f\n'|
{
found=0 ;found1=0;test "$e"&&found1=$(grep -c -e . "$dir"/dir.order)
any_new=0
>$dir/dir.order.tmp;>$dir/dir.order.tmp2
while read -er a;do test -f "$dir/$a"||continue
if test "$e"&&test $(grep -x -c "$dir"/dir.order -e "$a") -gt 0;then
found=$[found+1]
= "$a" >>$dir/dir.order.tmp
else
= "$a" >>$dir/dir.order.tmp2
any_new=1
fi;done

if test "$e";then
>$dir/dir.order.tmp3
nel <"$dir"/dir.order|
while read -er a;do
if test $(grep -x -c "$dir"/dir.order.tmp -e "$a") -gt 0;then
= "$a" >>$dir/dir.order.tmp3
fi;done
mv -f "$dir"/dir.order.tmp3 -T "$dir"/dir.order.tmp
fi

cat "$dir"/dir.order.tmp2 >>$dir/dir.order.tmp
nel -d <"$dir"/dir.order.tmp >"$dir"/dir.order.tmp2;rm "$dir"/dir.order.tmp
wr_over "$dir"/dir.order <"$dir"/dir.order.tmp2;rm "$dir"/dir.order.tmp2

ex=0
#test $found -eq $found1&&ex=2
test $any_new -gt 0&&ex=2
test $ex -gt 0&&{ = "updated" >/dev/stderr;exit $ex;}

nel <"$dir"/dir.order|{
if test "$arg" = "-l";then cat;else
while read -er a;do nel <${dir}/${a};done|nel -d
fi
};}