#!/bin/bash
# -*- mode: sh; fill-column: 75; tab-width: 8; coding: utf-8-unix -*-

shopt -s nullglob || exit 1

prog=`basename $0 .bash`
ROLE=base
export PATH=/sbin:$PATH

PREFIX=/usr/local
. /usr/local/bin/usr_local_tput.bash || exit 2

DEST=$PREFIX/portage/testforge/sec-keys
FROM=/usr/portage/sec-keys

cd /
grep /~sam/ /usr/portage/sec-keys/*/*d| \
  sed -e 's@.*/@@' -e 's/"//' -e 's/.*-//'|grep -v P | \
  while read f;do
    b=`ls /usr/portage/distfiles/*"$f"`|| continue;
    a=`readlink "$b"`;
    echo $a;[ -h "$a" ] && continue;
    echo $b;
  done | \
sed -e 's@\.\./\.\.@/i@'|zip -m9 --symlinks sam.zip -@

cd $FROM
#
tar cf - *-* | tar xf -  --keep-newer-files -C $DEST 2>/dev/null >/dev/null

[ -d $DEST ] || mkdir -p $DEST
cd $FROM
i=0
for dir in *-*; do
    [ -d $dir ] || continue
    [ -d $DEST/$dir ] || mkdir $DEST/$dir
    ls $dir/*ebuild >/dev/null 2>/dev/null || { WARN no *ebuild in $dir ; continue ; }
    for file in $dir/*ebuild ; do
	[ -f $DEST/$file ] && [ $DEST/$file -nt $FROM/$file ] && continue
	sed -e 's/^LICENSE=/RESTRICT="mirror"\nLICENSE=/' > $DEST/$file < $FROM/$file
	if grep -q 'Mirrored from ' $FROM/$file ; then
	    url="`grep 'Mirrored from ' $FROM/$file|sed -e 's/.*Mirrored from //' -e 's/ .*//'`"
	    if [ -n "$url" ] ; then
		i=`expr $i + 1`
		rep=`sed -e 's/[$]/\\\\$/g' -e 's/[&]/\\\\&/g' <<< $url`
		# could change some keyservers here
		rep=`sed -e 's/http:/https:/' <<< $rep`
		DBUG rep="$rep"
		sed -e "s@https://dev.gentoo.org/.sam/[^ \"]*@$rep@" \
		    -i $DEST/$file
	    fi
	fi
	cd $DEST/$dir
	for dfile in $dir/*ebuild ; do
	    ddir=`dirname $dfile`
	    cd $ddir
	    ebuild manifest *ebuild
	done
	cd $DEST
    done
done
INFO $i $DEST
