#!/bin/sh

# Author : Benoit PAPILLAULT <benoit.papillault@free.fr>
# Creation : 19/09/2003

# Find all files on an image that do no belong to any installed spells

# we use $IMAGE if defined, or else work/image
if [ -z "${IMAGE}" ]; then
    IMAGE="work/image"
fi
echo "using IMAGE=${IMAGE}"

# checking image
if [ ! -d "${IMAGE}" ]; then
    echo "${IMAGE} is not a directory"
    exit -1
fi

cd "${IMAGE}" || exit -1

# First, list of the files inside the image

find . | cut -b2- | sort -u -r > /tmp/gaze.found

# check for the file listing all installed spells
if [ ! -f var/state/sorcery/packages ]; then
    echo "missing /var/state/sorcery/packages"
    exit -1;
fi

# Second, get the list of installed spells

OIFS="${IFS}"
IFS=":"
(while read spell x y version;
do
	echo "${spell}-${version}"
done) < var/state/sorcery/packages > /tmp/file
IFS="${OIFS}"

# For each installed spell, get the list of installed files

(while read file;
do
  if [ ! -f "var/log/sorcery/install/${file}" ]; then
      echo "missing /var/log/sorcery/install/${file}"
      exit -1;
  fi
  cat "var/log/sorcery/install/${file}"
done) </tmp/file > /tmp/toto

sort -u -r /tmp/toto > /tmp/gaze.known

# we keep some alien files : 
# - /etc/sorcery/local : sorcery configuration
# - /var/state/sorcery : list of installed packages
# - /var/log/sorcery/install : list of installed files (only files
#   from installed packages need to be kept)
# - /var/log/sorcery/md5sum : same
# - /etc/sorcery & /var/lib/sorcery : where sorcery is installed (mainly)

diff -B /tmp/gaze.found /tmp/gaze.known | grep "^<" | cut -b 3- \
| grep -v "^/dev/" \
| grep -v "^/proc/" \
| grep -v "^/usr/src/linux/" \
| grep -v "^/usr/include/asm/" \
| grep -v "^/usr/include/asm-generic/" \
| grep -v "^/usr/include/linux/" \
| grep -v "^/etc/sorcery/" \
| grep -v "^/var/state/sorcery/" \
| grep -v "^/var/log/sorcery/" \
| grep -v "^/var/lib/sorcery/" > /tmp/alien.txt

# optional : remove directories from the list
(while read file;
do
  if [ ! -d "./${file}" ]; then
      if [ ! -L "./${file}" ]; then
          echo "${file}"
      fi
  fi
done) < /tmp/alien.txt > /tmp/alien_files.txt

echo "files to be removed are under /tmp/alien.txt and /tmp/alien_files.txt"

# remove alien files
exit

(while read file;
do
  if [ -d "./${file}" ]; then
      rmdir "./${file}"
  else
      rm "./${file}"
  fi
done) < /tmp/alien.txt
