# 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/redis/redis.conf.new
config etc/redis/sentinel.conf.new
config etc/logrotate.d/redis.new
preserve_perms etc/rc.d/rc.redis.new

# Create redis user/group:
if ! chroot . getent group redis >/dev/null
then
  GROUPOPT="-g 198"
  if chroot . groupadd $GROUPOPT redis 2>/dev/null
  then
    : redis group successfully added
  else
    chroot . groupadd redis
  fi
fi

if ! chroot . getent passwd redis >/dev/null
then
  USEROPT="-u 198"
  if chroot . useradd -g redis $USEROPT -d /var/lib/redis redis 2>/dev/null
  then
    : redis user successfully added
  else
    chroot . useradd -g redis -d /var/lib/redis redis
  fi
fi

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

if [ -x /etc/rc.d/rc.redis ]; then
  # Start Redis daemon
  echo "Starting Redis daemon:    /etc/rc.d/rc.redis start"
  /etc/rc.d/rc.redis start
fi
_EOM_
fi

( cd usr/bin ; rm -rf redis-check-aof )
( cd usr/bin ; ln -sf redis-server redis-check-aof )
( cd usr/bin ; rm -rf redis-check-rdb )
( cd usr/bin ; ln -sf redis-server redis-check-rdb )
( cd usr/bin ; rm -rf redis-sentinel )
( cd usr/bin ; ln -sf redis-server redis-sentinel )
