#!/bin/sh
#
ROOT=/
SVN_DIR=/home/svn
ETC_DIR=/etc
mkdir -p $SVN_DIR

HOST=`hostname`
case $# in
  1)
    TO_EMAIL=$1
    FROM_EMAIL=`echo $1 | sed -e s,@,+$HOST@,`
    ;;

  *)
    echo "Usage: mk-etc-repository email" 1>&2
    exit 1
    ;;

esac

# Make sure subversion + subversion-tools are installed
apt-get install -y subversion subversion-tools

# Install procmail + esmtp for simple mail notification
if test ! -f /usr/sbin/sendmail; then
    apt-get install -y procmail esmtp
    test -f /usr/sbin/sendmail || ln -s /usr/bin/esmtp /usr/sbin/sendmail
fi
if test ! -d $SVN_DIR/repos; then
    svnadmin create $SVN_DIR/repos
    chmod 700 $SVN_DIR
    chmod 700 $SVN_DIR/repos
    cat <<'EOF' > $SVN_DIR/README.SECURITY

Files stored in this directory and all the sub-directories must be owned
by root and must not be accessed by anybody.

- the /home/svn directory must have the rights: rwx------  (700)
- the 'last' and 'repos' directories must have the rights: rwx------ (700)

'repos' is the subversion repository which contains the '/etc/' files from
various servers.

'last' contains the last image of '/etc'

EOF
    svn import -m 'Initial import of $ETC_DIR' $ETC_DIR file://$SVN_DIR/repos/etc
    mkdir $SVN_DIR/last
    cd $SVN_DIR/last && svn co file://$SVN_DIR/repos/etc
    cd $SVN_DIR/last/etc && tar cf - `find . -name .svn` | (cd $ETC_DIR && tar xvf -)
fi

sed -e "s,commit-email.pl,commit-email.pl --from $FROM_EMAIL," \
    -e "s,commit-watchers@example.org,$TO_EMAIL," < $SVN_DIR/repos/hooks/post-commit.tmpl > $SVN_DIR/repos/hooks/post-commit 


sed -e "s,TO_EMAIL,$TO_EMAIL," \
    -e "s,FROM_EMAIL,$FROM_EMAIL," <<'EOF' > $ETC_DIR/cron.daily/archive-etc
#!/bin/sh
SVN_ETC=/etc
HOST=`hostname`

# Commit those changes
cd $SVN_ETC && svn commit -m "Saving changes in /etc on $HOST"

# Email address to which changes are sent
EMAIL_TO="TO_EMAIL"
STATUS=`cd $SVN_ETC && svn status`
if test "T$STATUS" != "T"; then
   (echo "Subject: New files in /etc on $HOST";
    echo "To: $EMAIL_TO";
    echo "The following files are new and should be checked in:";
    echo "$STATUS") | sendmail -f'FROM_EMAIL' $EMAIL_TO
fi

EOF

chmod +x $ETC_DIR/cron.daily/archive-etc $SVN_DIR/repos/hooks/post-commit
