#!/bin/sh
#
# etcdiff (deb-etcdiff?) shows how your current /etc dir
# diverges from the debian distribution standard one.
#
# Copyright (C) 2008 Antonio Ospite <ospite@studenti.unina.it>
# License: GPLv2 or later

set -ex

PROMPT_RM=-i

DEBIANMIRROR="http://ftp.it.debian.org/debian"

rm $PROMPT_RM -r temp     && mkdir temp
rm $PROMPT_RM -r archives && mkdir archives
rm $PROMPT_RM -r conf     && mkdir -p conf/patches

USERMODE="-perm /o+r"
MAXDEPTH="-maxdepth 1"

#FILES="/etc/sysctl.conf /etc/init.d/procps /etc/passwd-"
FILES=$(find /etc/ $MAXDEPTH -type f $USERMODE | grep -v '.dpkg-')

for file in ${FILES};
do
  echo "-> $file"

  # Find out what installed package provides the config file
  PACKAGE=$(dpkg-query -S "$file" | cut -d ':' -f 1 | uniq 2> /dev/null)

  # Copy the whole file if it is not provided by default
  if [ "x$PACKAGE" == "x" ];
  then
    cp "$file" conf/
    continue
  fi

  # Get the package from the repository and diff

  FILENAME=$(apt-cache show $PACKAGE | grep ^Filename | cut -d ' ' -f 2-)
  ARCHIVE=$(basename $FILENAME)

  (cd archives && wget -q -nc -c $DEBIANMIRROR/$FILENAME)
  dpkg -x archives/$ARCHIVE temp/

  diff -q temp/$file $file > /dev/null
  if [ $? -eq 1 ];
  then
    diff -u temp/$file $file > conf/patches/$(basename $file).patch
  else
    echo "$file: not changed"
  fi

done
