#!/bin/sh
#updates pets and db-entries in quirky local repos.
#140121 updated for new quirky build system.
#140131 make tar silent.
#140202 fix TARGETDB. 140204
#141027 ask before add new PET to repo.
#141106 amd64.

[ ! -f DISTRO_SPECS ] && exit
. ./DISTRO_SPECS #141106 has DISTRO_TARGETARCH (= x86 or amd64)

if [ ! "$DISTRO_TARGETARCH" ];then #141106
 echo "Error, DISTRO_TARGETARCH not defined in file DISTRO_SPECS"
 exit
fi

if [ -d sandbox3 ];then
 cd sandbox3
else
 echo
 echo "You need to run 3builddistro first, to build sandbox3/quirk*.usfs.xz"
 exit
fi

CURRDIR="`pwd`"
TARGETPATH="../../../pet-construction/${DISTRO_TARGETARCH}/pet_packages-${DISTRO_DB_SUBNAME}" #141106
[ ! -d ../../../pet-construction/${DISTRO_TARGETARCH}/pet_packages-${DISTRO_DB_SUBNAME} ] && mkdir -p ../../../pet-construction/${DISTRO_TARGETARCH}/pet_packages-${DISTRO_DB_SUBNAME}
#ex: DISTRO_COMPAT_VERSION=trusty DISTRO_FILE_PREFIX=tahr DISTRO_DB_SUBNAME=tahr
TARGETDB="$(find ../../../quirky/woof-distro/${DISTRO_TARGETARCH} -type f -name Packages-pet-${DISTRO_DB_SUBNAME}-official | tail -n 1)" #140204
[ ! "$TARGETDB" ] && exit 2
[ ! -f $TARGETDB ] && exit 2
LOCALPETS="../../../local-repositories/${DISTRO_TARGETARCH}/packages-pet"
[ ! -d ../../../local-repositories/${DISTRO_TARGETARCH}/packages-pet ] && exit 3

ALLPETS="$(find . -mindepth 1 -maxdepth 2 -type f -name '*.pet' | sed -e 's%^\./%%' | tr '\n' ' ')"

for APET in $ALLPETS
do
 BASEPET="`basename $APET`"
 [ -f ${TARGETPATH}/${BASEPET} ] && continue
 echo
 echo "Do you want to add ${BASEPET} to this PET repo?:" #141027
 echo "${TARGETPATH}"
 echo -n "ENTER only to add, any other char not to: "
 read targetyes
 [ "$targetyes" != "" ] && continue
 echo "Adding ${BASEPET}..."
 cp -a $APET ${TARGETPATH}/
 sync
 cd ${TARGETPATH}
 PKGNAME="`basename $BASEPET .pet`"
 [ -d $PKGNAME ] && rm -rf $PKGNAME
 tar -zxf $BASEPET 2>/dev/null #140131
 PETSPECS="`cat ${PKGNAME}/pet.specs`"
 [ ! "$PETSPECS" ] && echo "ERROR: no ${PKGNAME}/pet.specs found"
 cd ${CURRDIR}
 if [ "$PETSPECS" ];then
  DB_pkgname="`echo -n "$PETSPECS" | cut -f 1 -d '|'`"
  pPTN="^${DB_pkgname}|"
  grep -v "$pPTN" ${TARGETDB} > /tmp/quirky6-target-db #remove any prior same entry.
  mv -f /tmp/quirky6-target-db ${TARGETDB}
  echo "$PETSPECS" >> ${TARGETDB}
  sort ${TARGETDB} > /tmp/quirky6-target-db
  mv -f /tmp/quirky6-target-db ${TARGETDB}
 fi
 cp -a -f $APET ${LOCALPETS}/
 sync
done

echo '...done'
exit 0
###END###
