#!/bin/bash
# -*- mode: sh; tab-width: 8; encoding: utf-8-unix -*-

ROLE=base
DEBUG=1

shopt -s nullglob || exit 1

. /usr/local/bin/usr_local_tput.bash || exit 2
[ -f /etc/conf.d/hostname ] && . /etc/conf.d/hostname

if [ -n "$hostname" -a "$hostname" = "pentoo" ] ; then
    TO=/mnt/o/Cache/linuxPen19/var/cache/portage/packages
  elif [ -f /etc/dracut.conf.d/funtoo.conf ] ; then
    TO=/mnt/o/Cache/linuxFun64/var/cache/portage/packages
  elif [ -f /etc/dracut.conf.d/clipos.conf ] ; then
    TO=/mnt/o/Cache/linuxClipos/var/cache/portage/packages
  elif [ -d /mnt/o/Cache/linuxPen19/var/cache/portage/packages ] ; then
    TO=/mnt/o/Cache/linuxPen19/var/cache/portage/packages
  else
    exit 3
fi

[ -n "$TO" ] || { ERROR empty TO ; exit 4 ; }
[ -d $TO ] || { ERROR mkdir -p $TO ; exit 5 ; }
find $TO -type f -exec chmod 644 {} \; &

[ "$#" -eq 0 ] && set -- /usr/portage/packages

grep -v : /var/lib/portage/world | while read f; do \
    ls /var/db/repos/*/$f 2>/dev/null >/dev/null && continue;
    ls /var/local/portage/*/$f 2>/dev/null >/dev/null && continue;
    echo $f
    done |tee /var/lib/portage/world.dead

for root in $* ; do
    cd $root  || exit 2$?
    INFO $root

    find -L . -type l -delete 2>&1 | grep Too | \
	sed -e 's/.: Too.*//' -e 's/find: .//'|xargs rm -f
    find . -type f -exec chmod 644 {} \; &
    find *-* virtual pentoo -type f -name \*tbz2 -o -name \*qpkg.tar -o -name \*.xpak | grep -v '_sources\|_download_' | while read file ; do
        dir=$( dirname $file )
	[[ $dir =~ dev-python/nltk-data ]] && continue
	[[ $dir =~ sys-kernel/pentoo-sources ]] && continue
	[[ $dir =~ app-emulation/virtio-win ]] && continue
        [ -d $TO/$dir ] || { DBUG mkdir -p $TO/$dir ;  mkdir -p $TO/$dir ; }
	[ -h $TO/$file ] && [ -f $file ] && DBUG rm $TO/$file && rm $TO/$file
        if [ -f $TO/$file -a -f $file ] ; then
	    diff -q $TO/$file $file && rm -f $file && ln -s $TO/$file $file && continue
            echo WARN: exists $TO/$file $file && mv $file $TO/$file && ln -s $TO/$file $file && continue
	    fi
        [ ! -h $file ] && mv $root/$file $TO/$file && ln -s $TO/$file $root/$file && 	DBUG ln -s $TO/$file  $root/$file && continue || exit 1
	DBUG dunno $file `ls -lF $TO/$file $file`
      done

    pushd $TO
    #  -o -name \*.xpak
    find *-* virtual pentoo -type f -name \*tbz2 -o  -name \*.tar | grep -v '_sources\|_download_' | while read file ; do
	[ -h $root/$file ] && [ -f $file ] && continue
	dir=`dirname  $root/$file`
	[ -d $dir ] || mkdir $dir
	ln -s $TO/$file $root/$file
      done
    popd
  done
exit 0
