#!/bin/sh -

# pop - pop files out of a subdirectory
# Steve Kinzler, steve@kinzler.com, Nov 93/Jun 03
# https://kinzler.com/me/home.html#unix

# Moves the files in each given directory to the directory's parent
# directory and deletes the directory.  The directory name may be the same
# as one of its files.

force=; bad=

while :
do
	case $# in
	0)	break;;
	*)	case "$1" in
		-f)	force=t;;

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

case "$#,$bad" in
0,*|*,?*)	cat << EOF 1>&2
usage: $0 [ -f ] directory ...
	-f	force file overwrites and directory replacements
EOF
		exit 1;;
esac

for dir
do
(
	cd "$dir" || exit

	wd=`pwd`
	bn=`basename "$wd"`

	if test -f ../POP$$ -o -d ../POP$$
	then
		echo "$0: cannot rename $wd to POP$$, already exists" 1>&2
		exit
	else
		trap 'echo "$0: aborting $wd pop, left as POP$$" 1>&2; exit' \
			1 2 13 15
		cd ..	       || exit
		mv "$bn" POP$$ || exit
		cd POP$$       || exit
	fi

	ls -a | sed '/^\.$/d; /^\.\.$/d; s/[ 	]/\\&/g' |
	while read file
	do
		if test -f ../"$file" -o -d ../"$file"
		then
			case "$force" in
			?*)	rm -r ../"$file" && mv "$file" ..;;
			*)	cat << EOF 1>&2
$0: cannot pop $wd/$file, already exists above
EOF
				;;
			esac
		else
			mv "$file" ..
		fi
	done

	if test `ls -a | sed '/^\.$/d; /^\.\.$/d' | wc -l` -gt 0
	then
		echo "$0: $wd pop unfinished, left as POP$$" 1>&2
	else
		cd .. && rmdir POP$$
	fi
)
done
