#!/usr/bin/perl -w

=head1 NAME

    mk-memcached-package-files - создание файлов для пакета с memcached

=head1 DESCRIPTION

    config, init, logrotate, 
    допустимые параметры:
    -d port=NNN - порт, который сервер будет слушать
    -d mem=NNN - ограничение по памяти, в мегабайтах
    -d conn=NNN - максимальное количество одновременных коннектов

=cut

use strict;
use warnings;

use SvnRelease::MkFiles;

my $mkfiles = SvnRelease::MkFiles->new(
    files => [
        {tmpl => 'init_d', file => "/etc/init.d/memcached-[% instance %]", perm => 0755, },
        {tmpl => 'config', file => "/etc/memcached/[% instance %].conf", },
        {tmpl => 'logrotate_d', file => "/etc/logrotate.d/memcached-[% instance %]", },
        {tmpl => 'monrun_conf', file => "/etc/monrun/conf.d/memcached-[% instance %].conf", },
        {tmpl => 'debian_postinst', file => "/DEBIAN/postinst", perm => 0755, },
        {tmpl => 'debian_postrm', file => "/DEBIAN/postrm", perm => 0755, },
        ],
    templates_fh => \*DATA,
    substvars => {
        'memcached:Depends' => join(', ',
                                'memcached',
                                'logrotate',
            ),
        'memcached:Conflicts' => 'apparmor',
    },
    );

my ($instance, @dummy) = $mkfiles->parse_options("instance_name");
if (@dummy || $instance !~ /^[a-z0-9_\-]+$/) {
    $mkfiles->usage();
}

$mkfiles->{vars}->{instance} = $instance;
$mkfiles->{vars}->{port} ||= 11211;

$mkfiles->mk();

__DATA__
<< logrotate_d
# rotate mysql logs
/var/log/memcached-[% instance %]/memcached.log {
	daily
	rotate 7
	missingok
	notifempty
	create 644 nobody root
	compress
	sharedscripts
	#postrotate
		#if [ -e /var/run/memcached-[% instance %].pid ] ; then
		#	pid=`cat /var/run/memcached-[% instance %].pid`;
		#	cmd=`cat /proc/$pid/cmdline | tr "\000" "\n"|head -n 1 |cut -d : -f 1`
		#	if [ "$cmd" == "/usr/bin/memcached" ]; then
		#		kill -HUP $pid
		#	fi;
		#fi
	#endscript
}


<< debian_postinst
#!/bin/bash -e

. /usr/share/debconf/confmodule

mkdir -p /var/log/memcached-[% instance %]
chown -R nobody:nogroup /var/log/memcached-[% instance %]

update-rc.d -f memcached remove >/dev/null
update-rc.d memcached-[% instance %] defaults >/dev/null


<< debian_postrm
#!/bin/bash -e

. /usr/share/debconf/confmodule

update-rc.d -f memcached-[% instance %] remove >/dev/null


<< config
# Run memcached as a daemon. This command is implied, and is not needed for the
# daemon to run. See the README.Debian that comes with this package for more
# information.
-d

# Log memcached's output to /var/log/memcached
logfile /var/log/memcached-[% instance %]/memcached.log

# Start with a cap of 64 megs of memory. It's reasonable, and the daemon default
# Note that the daemon will grow to this size, but does not start out holding this much
# memory
-m [% mem || 1024 %]

# Connection port
-p [% port %]

# Run the daemon as root. The start-memcached will default to running as root if no
# -u command is present in this config file
-u nobody

# Specify which IP address to listen on. The default is to listen on all IP addresses
# This parameter is one of the only security measures that memcached has, so make sure
# it's listening on a firewalled interface.
# -l 127.0.0.1

# Limit the number of simultaneous incoming connections. The daemon default is 1024
-c [% conn || 8192 %]

# Lock down all paged memory. Consult with the README and homepage before you do this
# -k

# Return error when memory is exhausted (rather than removing items)
# -M

# Maximize core file limit
# -r

<< init_d
#! /bin/bash
### BEGIN INIT INFO
# Provides:          memcached
# Required-Start:    $syslog
# Required-Stop:     $syslog
# Should-Start:      $local_fs
# Should-Stop:       $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description:    memcached - Memory caching daemon
# Description:        memcached - Memory caching daemon
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/bin/memcached
DAEMONNAME=memcached
DAEMONBOOTSTRAP=/usr/share/memcached/scripts/start-memcached
DESC=memcached

test -x $DAEMON || exit 0
test -x $DAEMONBOOTSTRAP || exit 0

set -e

ulimit -n 65536

CONFIG="/etc/memcached/[% instance %].conf"
PIDFILE="/var/run/memcached-[% instance %].pid"

case "$1" in
    start)
        echo -n "Starting $DESC: "
        start-stop-daemon --start --quiet --exec "$DAEMONBOOTSTRAP" -- $CONFIG $PIDFILE
        echo "$NAME."
        ;;
    stop)
        echo -n "Stopping $DESC: "
        start-stop-daemon --stop --quiet --oknodo --pidfile $PIDFILE --exec $DAEMON
        echo "$NAME."
        rm -f $PIDFILE
        ;;

    restart|force-reload)
    #
    #   If the "reload" option is implemented, move the "force-reload"
    #   option to the "reload" entry above. If not, "force-reload" is
    #   just the same as "restart".
    #
        echo -n "Restarting $DESC: "
        start-stop-daemon --stop --quiet --oknodo --pidfile $PIDFILE
        rm -f $PIDFILE
        sleep 1
        start-stop-daemon --start --quiet --exec "$DAEMONBOOTSTRAP" -- $CONFIG $PIDFILE
        echo "$NAME."
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|force-reload}" >&2
        exit 1
        ;;
esac

exit 0


<< monrun_conf
[memcached-[% instance %]]
execution_interval=60
execution_timeout=30
command=(echo stats | nc -w 1 127.0.0.1 [% port %] | grep -q pid) && echo '0;Ok' || echo '2;No running memcached.'

