+#!/bin/sh
+
+_get_unpack_package()
+{
+ PACKAGE=$1
+ FILEPATH=$(apt-cache show $PACKAGE | grep ^Filename | cut -d ' ' -f 2-)
+
+ if [ "x$FILEPATH" = "x" ];
+ then
+ echo "Package '$PACKAGE' does not exist."
+ exit 1
+ fi
+
+ ARCHIVE=$(basename $FILEPATH)
+
+ wget -q -nc -c $DEBIANMIRROR/$FILEPATH -P $CACHEDIR && \
+ ([ -d $TEMPDIR/$PACKAGE ] || mkdir $TEMPDIR/$PACKAGE) && \
+ dpkg -x $CACHEDIR/$ARCHIVE $TEMPDIR/$PACKAGE
+}
+
+_do_etcdiff()
+{
+ ETCBASEDIR=$1
+ PREFIX=$2
+
+ REPORT_NAME=$(basename $ETCBASEDIR)
+
+ # Report diff between debian conf and our local one
+ rm -f $REPORTDIR/$REPORT_NAME.diff
+ find $PREFIX/etc -type f | \
+ while read file;
+ do
+ diff -ruN $ETCBASEDIR/${file#$PREFIX/} ${file#$PREFIX} >> $REPORTDIR/$REPORT_NAME.diff
+ done
+
+ # Report symlinks in /etc
+ rm -f $REPORTDIR/$REPORT_NAME.symlinks
+ find $PREFIX/etc -type l | \
+ while read file;
+ do
+ stat -c '%N' $file >> $REPORTDIR/$REPORT_NAME.symlinks
+ done
+}
+
+etchdiff_system()
+{
+ PACKAGES=$(dpkg --get-selections | grep 'install$' | cut -f 1 -d ' ')
+
+ rm $PROMPT_RM -rf $TEMPDIR/__debian_etc && mkdir $TEMPDIR/__debian_etc
+
+ for p in $PACKAGES;
+ do
+
+ # Skip packages which don't put anything in /etc
+ if ! dpkg -L $p | grep -q '/etc/';
+ then
+ continue
+ fi
+
+ echo "Getting package $p..."
+ _get_unpack_package $p
+
+ # save the original etc dir for later processing
+ cp -ir $TEMPDIR/$PACKAGE/etc $TEMPDIR/__debian_etc
+ done
+
+ _do_etcdiff $TEMPDIR/__debian_etc
+
+ rm -rf $TEMPDIR/__debian_etc
+}
+
+etcdiff_by_package()
+{
+ PACKAGE=$1
+
+ if dpkg --status $PACKAGE | grep -q 'not-installed';
+ then
+ echo "Package '$PACKAGE' not installed"
+ return 1
+ fi
+
+ # Skip packages which don't put anything in /etc
+ if ! dpkg -L $PACKAGE | grep -q '/etc/';
+ then
+ echo "$PACKAGE does not put any file in /etc"
+ return 1
+ fi
+
+ _get_unpack_package $PACKAGE
+
+ _do_etcdiff $TEMPDIR/$PACKAGE $TEMPDIR/$PACKAGE
+
+ return 0
+}
+
+etcdiff_by_file()
+{
+ FILE=$1
+
+ if [ ! -e $FILE ];
+ then
+ echo "ERROR, file $FILE does not exist."
+ return 1;
+ fi
+
+ if [ ! -f $FILE ];
+ then
+ echo "ERROR, file $FILE is not a regular file."
+ return 1;
+ fi
+
+ if [ $FILE = ${FILE#/etc/} ];
+ then
+ echo "ERROR, file path must begin with /etc/."
+ return 1;
+ fi
+
+ # Find out which installed package provides the config file
+ PACKAGE=$(dpkg-query -S "$FILE" | cut -d ':' -f 1 | uniq 2> /dev/null)
+
+ REPORT_NAME=$(basename $FILE)
+
+ if [ "x$PACKAGE" = "x" ];
+ then
+ diff -ruN /dev/null $FILE > $REPORTDIR/$REPORT_NAME.diff
+ else
+ _get_unpack_package $PACKAGE
+ diff -ruN $FILE $TEMPDIR/$PACKAGE/$FILE > $REPORTDIR/$REPORT_NAME.diff
+ fi
+
+ if [ $(stat -c '%s' $REPORTDIR/$REPORT_NAME.diff) -eq 0 ];
+ then
+ rm -f $REPORTDIR/$REPORT_NAME.diff
+ fi
+}