#!/bin/bash

# free disk space
freedisk()
{
   df $BUILDS | tail -n 1 | tr -s " " | cut -d " " -f 4
}


# $1 = source dir (eg $SLAX or $SLACKWARE)
# $2 = package name
# $3 = target
pkg_install()
{
   local PKG NAME

   NAME=$(echo $2 | sed -r 's/(.)/[\1]/g')

   for PKG in $(find $1 | egrep "/$NAME-[^-]+-[^-]+-[^-]+.tgz\$"); do
     installpkg -root $3 $PKG >/dev/null
   done
   if [ "$PKG" = "" ]; then
      echo "- package not found"
   fi
}

# $1 = from
copyroot()
{
   if [ -d $CWD/system/$1/root ]; then
      cp -Ra $CWD/system/$1/root/* $1
   fi
}

doit()
{
   mkdir -p $BUILDS/$1
   mount -o remount,add:0:$BUILDS/$1=rw aufs $UNION
   mount -o remount,mod:$LASTBR=ro aufs $UNION
   LASTBR=$BUILDS/$1

   cat $CWD/system/$1/pkglist | sed -r "s/#.*//" | while read LINE; do
       TYPE=$(echo $LINE | cut -d ':' -f 1)
       PACKAGE=$(echo $LINE | cut -d ':' -f 2)
       if [ ! "$PACKAGE" -o ! "$TYPE" ]; then continue; fi

       echo $LINE
       if [ "$TYPE" = "slackware" ]; then
          pkg_install $SLACKWARE $PACKAGE $UNION
       else
          pkg_install $SLAX $PACKAGE $UNION
       fi
   done

   # if kernel modules were added, update dependencies
   if [ "$(find $LASTBR/lib/modules/ -name "*.ko" 2>/dev/null | head -n 1)" != "" ]; then
      depmod -b $UNION
   fi
   
   # update libraries cache
   ldconfig -r $UNION
}

# remove files which are already installed in $1
# so the module won't include duplicated files
# $1 = original files root (source for comparing)
# $2 = new files root, remove duplicates from here
#
function remove_duplicates()
{
   find "$2" | while read DUPLICATE; do
      ORIGFILE=$1/"${DUPLICATE:$((${#2}+1))}"
      if [ "$DUPLICATE" = "$ORIGFILE" ]; then continue; fi

      # if one file is a symlink and the other one is not, don't delete anything
      if [ -h "$DUPLICATE" -a ! -h "$ORIGFILE" ]; then continue; fi
      if [ ! -h "$DUPLICATE" -a -h "$ORIGFILE" ]; then continue; fi

      # a symlink pointing to the same location can be removed
      if [ -h "$DUPLICATE" -a -h "$ORIGFILE" ]; then
         if [ "$(readlink "$DUPLICATE")" = "$(readlink $ORIGFILE)" ]; then
            rm -v "$DUPLICATE"
            rmdir --ignore-fail-on-non-empty "$(dirname $DUPLICATE)"
            continue
         fi
      fi

      # existing files will be tested for UID and diff'ed
      if [ ! -d "$DUPLICATE" -a -a "$ORIGFILE" ]; then
         if [ "$(stat $ORIGFILE | grep Uid)" = "$(stat $DUPLICATE | grep Uid)" ]; then
            diff --brief "$DUPLICATE" "$ORIGFILE" >/dev/null 2>/dev/null
            if [ $? = 0 ]; then # is the same, can be removed
               rm -v "$DUPLICATE"
               rmdir --ignore-fail-on-non-empty "$(dirname $DUPLICATE)"
            fi
         fi
      fi
   done
}
