#!/bin/sh
#sd card with gentoo 8gb card for raspberry pi, assume 2nd partition mounted on /mnt/sdb2

for APKGSPEC in `find /mnt/sdb2/var/db/pkg -mindepth 2 -maxdepth 2 -type d | grep -v 'pkg/virtual' | tr '\n' ' '`
do
 #ex: /mnt/sdb2/var/db/pkg/sys-fs/e2fsprogs-1.42
 APKGNAME="`basename $APKGSPEC`"
 echo "$APKGNAME"
 #[ -d ./${APKGNAME} ] && rm -rf ./${APKGNAME}
 if [ -f ${APKGSPEC}/CONTENTS ];then
  mkdir ${APKGNAME}
  [ -f ${APKGSPEC}/CATEGORY ] && cp -a ${APKGSPEC}/CATEGORY ${APKGNAME}/
  [ -f ${APKGSPEC}/DESCRIPTION ] && cp -a ${APKGSPEC}/DESCRIPTION ${APKGNAME}/
  [ -f ${APKGSPEC}/DEPEND ] && cp -a ${APKGSPEC}/DEPEND ${APKGNAME}/
  [ -f ${APKGSPEC}/RDEPEND ] && cp -a ${APKGSPEC}/RDEPEND ${APKGNAME}/
  [ -f ${APKGSPEC}/SIZE ] && cp -a ${APKGSPEC}/SIZE ${APKGNAME}/
  cat ${APKGSPEC}/CONTENTS | tr '\t' ' ' | tr -s ' ' |
  while read ALINE
  do
   ATYPE="`echo -n "$ALINE" | cut -f 1 -d ' '`"
   case $ATYPE in
    dir)
     ADIR="`echo -n "$ALINE" | cut -f 2-9 -d ' '`"
     [ -d /mnt/sdb2"${ADIR}" ] && mkdir -p "${APKGNAME}${ADIR}"
    ;;
    obj)
     #need be careful, may have space chars in path...
     AFILE="`echo -n "$ALINE" | rev | cut -f 3-9 -d ' ' | rev | cut -f 2-9 -d ' '`"
     if [ -e /mnt/sdb2"${AFILE}" ];then
      APATH="`dirname "$AFILE"`"
      [ ! -e "${APKGNAME}${APATH}" ] && mkdir -p "${APKGNAME}${APATH}"
      cp -a -f --remove-destination /mnt/sdb2"${AFILE}" "${APKGNAME}${APATH}"/
     fi
    ;;
    sym)
     ASYM="`echo -n "$ALINE" | cut -f 2 -d ' '`"
     if [ -e /mnt/sdb2"${ASYM}" ];then
      APATH="`dirname "$ASYM"`"
      [ ! -e "${APKGNAME}${APATH}" ] && mkdir -p "${APKGNAME}${APATH}"
      cp -a -f --remove-destination /mnt/sdb2"${ASYM}" "${APKGNAME}${APATH}"/
     fi
    ;;
   esac
  done
 fi
 sync
done

###END###
