#!/bin/sh
set -e -f -u -x
tool="${0%\/*}"/..

while [ $# -gt 0 ]
 do case $1 in
	 (--) shift; break;;
	 (*=*) eval "$1"; shift;;
	 (*) break;;
	 esac
 done

host=${host:-autogeree.net}
path=${path:-pub/www/img}
root=/tmp/tool/webimg
d=$1; shift
htpasswd=/home/"$USER"/var/lib/apache2/img/"$d"/.htpasswd

(
cd "$root" &&
if [ ${password:+set} ]; then
	cat >$d/.htaccess <<-EOF &&
		AuthName "$user"
		AuthType Basic
		Require  Valid-User
		AuthUserFile $htpasswd
		EOF
	ssh "$host" \
		mkdir -p "$(dirname "$htpasswd")" '&&' \
		htpasswd -s -b -c "$htpasswd" "$user" "$password"
else
	cat >$d/.htaccess <<-EOF
		EOF
fi &&
rsync -e ssh \
 --chmod=Du+rwx,Dg+rx,Dg-w,Do-rwx,Fug+r,Fugo-wx,Fug+w,Fo-rwx \
 --compress \
 --delete \
 --delete-excluded \
 --human-readable \
 --inplace \
 --itemize-changes \
 --links \
 --partial \
 --perms \
 --progress \
 --recursive \
 --relative \
 --times \
 "$@" \
 webimg.ico \
 "$d" "$host":"$path"/
)
