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

# shopt -s nullglob

[ -f /etc/conf.d/hostname ] && . /etc/conf.d/hostname

if [ $# -eq 1 ] ; then
    TO=$1
  elif [ -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
  else
    exit 3
fi

[ -n "$TO" ] || { echo ERROR: empty TO ; exit 4 ; }
[ -d $TO ] || { echo ERROR: mkdir -p $TO ; exit 5 ; }

    pushd $TO
    #  -o -name \*.xpak
    find *-* virtual pentoo -type f -name \*tbz2 | grep -v '_sources\|_download_' | while read file ; do
	dir=`dirname  $file`
	base=`basename $file`
	subdir=`sed -e 's/-[0-9].*//' <<< $base`
	xdir=$dir/$subdir
	[ -d $xdir ] || continue
	xpak=`sed -e 's/.tbz2/-?.xpak/' <<< $base`
	ls $file $xdir/$xpak 2>/dev/null && rm -f  $xdir/$xpak
      done
    popd

    cd $OUT
    rm -rf  sys-firmware/intel-microcode* \
       sys-kernel/linux-firmware/* qpkg.*

     find -L *-*/ -type l -delete 2>&1| \
	 grep 'Too many levels'| \
	 sed -e 's/find: .//' -e 's/xpak.:.*/xpak/'| \
	 xargs rm -f

 exit 0
