#!/bin/sh -e
# $Id: sisyphus_link_move,v 1.1.1.1 2005/05/18 15:23:21 legion Exp $

. /etc/sisyphus/functions
. /etc/sisyphus/config

cd "$PREFIX"

LANG=C
PROG="${0##*/}"
WORKDIR="$(mktemp -d -t "$PROG.XXXXXXXXXX")"
interactive=
to=
with_bin=
source_arch=
dest_arch=

Usage() {
    [ "$1" = 0 ] || exec >&2
    cat << EOF
Usage: $PROG [rpms|srpms] LISTNAME [<name> ...]

Options:
	-a, --all              used with the 'srpms'
    -s, --source-arch      
    -d, --dest-arch        
    -i, --interactive      read 'name' from stdin.
    -h, --help             show this message
EOF
    [ -n "$1" ] && exit "$1" || exit
}

bin() {
  local binname="$1" && shift
  local l list listarch
  
  find files/ ! -name 'list.src.*' -name "list${source_arch:+.$source_arch}.*" -type f | 
  while read l; do
	list="${l##*/}"
	list="${list%.*}"
	listarch="${list##*.}"
	[ -z "$dest_arch" ] || listarch="$dest_arch"

	[ "list.$listarch.$to" != "$list" ] || continue
	
	[ -f "files/list.$listarch.$to" ] || 
	  { Info "file not found: files/list.$listarch.$to"; continue; }

	if grep "^$binname[[:space:]]" "$l" >> "files/list.$listarch.$to"; then
	  subst "\,^$binname[[:space:]],d" "$l"
	fi
  done
}

find_bin() {
  local srcname="$1" && shift
  lists="$(find files/ ! -name 'list.src.*' -name "list${source_arch:+.$source_arch}.*" -type f -print0)"
  [ -n "$lists" ] || return
  grep "^[^[:space:]]\+[[:space:]]\+$srcname$" $lists
}

src() {
  local srcname="$1" && shift
  local l

  [ -f "files/list.src.$to" ] || 
	{ Info "file not found: files/list.src.$to"; return; }

  find files/ ! -name "list.src.$to" -name 'list.src.*' -type f | 
  while read l; do
	[ -f "files/list.src.$to" ] || 
	  { Info "file not found: files/list.src.$to"; continue; }

	if grep "^$srcname[[:space:]]" "$l" >> "files/list.src.$to"; then
	  subst "\,^$srcname[[:space:]],d" "$l"
	fi
  done
  [ -n "$with_bin" ] || return 0

  local b binlist="$(find_bin "$srcname")"
  [ -n "$binlist" ] || return 0
  for b in $binlist; do
	bin "$b"
  done
}

exit_handler() {
	local rc=$?
	trap - EXIT
	[ -z "$WORKDIR" ] || rm -rf -- "$WORKDIR"
	exit $rc
}

trap exit_handler HUP INT QUIT TERM EXIT

TEMP=`getopt -n $PROG -o h,i,A: -l help,interactive,arch: -- "$@"` || Usage
eval set -- "$TEMP"

while :; do
    case $1 in
        -A| --arch) shift
            [ -z "$1" ] || rarch="$1"
            ;;
        -i| --interactive) interactive=1
            ;;
	-h| --help) Usage 0
	    ;;
	--) shift; break
	    ;;
	*) Fatal "unrecognized option: $1"
	    ;;
    esac
    shift
done

# At least one argument, please.
if ! [ "$#" -ge 4 ]; then
	Info "at least two arguments is required."
	Usage
fi

action="$1" && shift
from="$1" && shift
to="$1" && shift
packags="$@"

if [ -n "$interactive" ]; then
    arg=
    while read arg; do
        packags="$packags $arg"
    done
fi

for p in $packags; do
  case $action in
	rpms)  bin "$p" ;;
	srpms) src "$p" ;;
  esac
done
