#!/bin/bash

myver="0.7.9"

#
# Copy&pasted from FST/source/include/util.sh, kept in sync manually by
# boobaa@.
#
Farchs=('i686' 'x86_64')

usage()
{
	man fwmirror
}

die()
{
	echo -e "$0: $*"
	exit 1
}

# turns "foo,bar var" to "var=('foo' 'bar')"
parse_coma()
{
	eval `echo $1|sed "s/^\(.\)/$2=('\1/;s/,/' '/g;s/\(.\)$/\1')/"`
}

in_array()
{
	local i=""
	local needle=$1
	shift 1

	# array() undefined
	[ -z "$1" ] && return 1
	for i in $*
	do
		[ "$i" == "$needle" ] && return 0
	done
	return 1
}

while [ "$#" -ne "0" ]; do
	case $1 in
		--)
			shift
			break
			;;
		--help)
			usage
			exit 0
			;;
		--version)
			echo "fwmirror (pacman-tools) $myver"
			echo
			echo "Copyright (c) 2006 by Miklos Vajna <vmiklos@frugalware.org>"
			echo "This is free software; see the source for copying conditions.  There is NO"
			echo "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
			exit 0
			;;
		-a)
			parse_coma $2 myarchs
			shift 1
			;;
		-d)
			dir="$2"
			shift 1
			;;
		-s)
			server="$2"
			shift 1
			;;
		-v)
			parse_coma "$2" versions
			shift 1
			;;
		-l)
			login="$2"
			shift 1
			;;
		-n)
			name="$2"
			shift 1
			;;
		*)
			usage
			exit 1
			;;
	esac
	shift 1
done

# custom rsync options
rsync_opts="$*"

# sanity checks
[ ${#myarchs[@]} -gt 0 ] || die "No architectures to sync, that's fine with me!"
[ -d "$dir" ] || die "$dir is not a directory!"
[ -n "$server" ] || die "No server specified! Should i mirror from /dev/random? ;-)"
[ ${#versions[@]} -gt 0 ] || die "No versions to sync, nothing to do!"
[ "`type -p rsync`" ] || die "Can't find rsync! Please install it with 'pacman -S rsync'!"

# exclude the non-requested archs
for i in "${Farchs[@]}"
do
	if ! in_array $i ${myarchs[@]}; then
		rsync_opts="$rsync_opts --exclude /frugalware-$i/"
	fi
done

# exclude source if not requested
if ! in_array source ${myarchs[@]}; then
	rsync_opts="$rsync_opts --exclude /source/ --exclude /_darcs/ --exclude /.git/"
fi

# the funny part
for i in "${versions[@]}"
do
	rsync -ay $rsync_opts "$server/frugalware-$i/" "$dir/frugalware-$i"
done
