# Handle the incoming configuration files:
config() {
  for infile in $1; do
    NEW="$infile"
    OLD="$(dirname $NEW)/$(basename $NEW .new)"
    # If there's no config file by that name, mv it over:
    if [ ! -r $OLD ]; then
      mv $NEW $OLD
    elif [ "$(cat $OLD | md5sum)" = "$(cat $NEW | md5sum)" ]; then
      # toss the redundant copy
      rm $NEW
    fi
    # Otherwise, we leave the .new copy for the admin to consider...
  done
}

preserve_perms() {
  NEW="$1"
  OLD="$(dirname $NEW)/$(basename $NEW .new)"
  if [ -e $OLD ]; then
    cp -a $OLD ${NEW}.incoming
    cat $NEW > ${NEW}.incoming
    mv ${NEW}.incoming $NEW
  fi
  config $NEW
}

config etc/icecast/icecast.xml.new
preserve_perms etc/rc.d/rc.icecast.new

# Only way to create and use the correct uid and gid on the target system,
# is to use chroot:
chroot . <<EOR 2>/dev/null
# Add the 'icecast' group if it doesn't exist already.
/usr/sbin/groupadd icecast 2> /dev/null

# Add the 'icecast' user if it doesn't exist already
/usr/sbin/useradd -c "Icecast" -d /usr/share/icecast \
  -g icecast -s "/bin/false" icecast 2> /dev/null

# Configure the home directory
chown -R icecast:icecast usr/share/icecast
chmod 750 usr/share/icecast

# Configure the conf directory
chown -R icecast:icecast etc/icecast
chmod 750 etc/icecast

# Configure the log directory
chown -R icecast var/log/icecast
chmod 750 var/log/icecast
EOR

#
# Update rc.local so that Icecast will be started on boot
#
if ! grep "rc.icecast" etc/rc.d/rc.local 1>/dev/null 2>&1 ; then
  cat <<_EOM_ >> etc/rc.d/rc.local

if [ -x /etc/rc.d/rc.icecast ]; then
  # Start Icecast server
  echo "Starting icecast:    /etc/rc.d/rc.icecast start"
  /etc/rc.d/rc.icecast start
fi
_EOM_
fi

