#!/bin/sh -efu
#
# Copyright (C) 2010  Paul Wolneykien <manowar@altlinux.org>
#
# This file is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
#

. shell-error
. shell-quote
. shell-args
. shell-config

show_help()
{
	cat <<EOF
Usage: $PROG [options] command configuration-archive.tar.gz

$PROG applies a Zabbix node configuration from an archive produced by the grow-zabbix-node program.


* Commands *

  The program is responsible for the following set of commands.

    apply

    By this command the new configuration is applied completely. The target database is dropped if it exists, so ALL OF THE DATA IS MISSING (overwritten). All configuration files are overwritten.

    switch

    By this command first an attempt is made to use an existing database. If the database exists it is left untouched. Otherwise the \`apply' command is executed. All configuration files are overwritten anyway.


* Main options *

  The root directory to extract files to:

  -r PATH, --root-dir=PATH

  Defaults to \`/'.

  The name and password of the database administrator user:

  -u ADMIN, --user=ADMIN
  -p [PASSWD], --password[=PASSWD]

  The default user name is \`root'. If the PASSWD argument is omitted then it is expected at the process standard input.

* Auxiliary options *

  -c CSNAME, --charset=CSNAME		the name of the charset to use loading the dump.


* Usage options *

  The following options control the program execution:

  -h, --help		print this help information;
  --usage		print short program usage information;
  -V, --version		print the program version and license terms;
  -v, --verbose		print information messages while processing the input;
  -q, --quiet		do not print any information messages.


  Please, report bugs to http://bugs.altlinux.ru/

EOF
	exit
}

print_version()
{
	cat <<EOF
$PROG version 1.0
Written by Paul Wolneykien <manowar@altlinux.org>

Copyright (C) 2010 Paul Wolneykien <manowar@altlinux.org>
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.
EOF
	exit
}

OPTS=`getopt -n $PROG \
              -o r:,u:,p::,c:h,V,v,q \
              -l root-dir:,user:,password::,charset:,help,usage,version,verbose,quiet -- "$@"` \
	|| show_usage
eval set -- "$OPTS"

ROOT_DIR=;USER=;PASSWORD_PRESENT=;PASSWORD=;CSNAME=;VERBOSE=;QUIET=

ROOT_DIR="/"

while :; do
	case "$1" in
		-r|--root-dir) ROOT_DIR="$2"; shift;;
		-u|--user) USER="$2"; shift;;
		-p|--password) PASSWORD_PRESENT="$1"; PASSWORD="$2"; shift;;
		-c|--charset) CSNAME="$2"; shift;;
		-h|--help) show_help;;
		--usage) show_usage;;
		-V|--version) print_version;;
		-v|--verbose) VERBOSE="$1";;
		-q|--quiet) QUIET="$1";;
		--) shift; break;;
		*) fatal "unrecognized option: $1";;
	esac
	shift
done

[ -n "$QUIET" ] || verbose=$VERBOSE

[ -n "${1:-}" ] || fatal "Specify a command and a .tar.gz archive"
COMMAND="$1"
[ "$COMMAND" = "apply" ] || [ "$COMMAND" = "switch" ] || fatal "Unrecognized command"

[ -n "${2:-}" ] || fatal "Specify a .tar.gz archive with the node configuration"
CONFIGA="$2"
[ -r "$CONFIGA" ] || fatal "Configuration archive is not readable"

#cleanup_handler()
#{
#	rm -rf "${workdir:-}"
#}
#trap cleanup_handler EXIT
#trap cleanup_handler HUP PIPE INT QUIT TERM
#
#workdir="$(mktemp -dt "$PROG.XXXXXXXXXX")"
#[ -d "$workdir" ] || fatal "Unable to create the work directory"

if [ -n "$PASSWORD_PRESENT" ] && [ -z "$PASSWORD" ]; then
	read -s -p "Password:" PASSWORD
fi

[ -n "$CSNAME" ] || CSNAME="utf8"

# Reads a metadata value.
# args: name
read_metadata() {
	tar xzOf "$CONFIGA" etc/zabbix/NODE \
	| sed -n -e "s/^$1: //p"
}

# Runs an SQL command (query).
# args: db-type cmd [db-name]
run_sql_cmd() {
	case "$1" in   #TODO: catch an exit code of expect
		mysql) expect -f - <<EOF | sed -e '/^Enter password:.*/ d';;
spawn -noecho sh -s -c "echo \\"$2\\" | mysql -B -u root -p \\"--default-character-set=$CSNAME\\" ${3:-}"
expect "*?assword:*" { send "$PASSWORD\\r" } eof { exit 1 }
expect { "*\n" { exp_continue } eof { exit } }
EOF
		*) fatal "Sorry, no support for \`$1' database yet.";;
	esac
}

# Runs an SQL script.
# args: db-type file [db-name]
run_sql_script() {
	[ -r "$2" ] || fatal "Unable to read file $2"
	verbose "Running SQL script $2"
	case "$1" in   #TODO: catch an exit code of expect
		mysql) expect -f - <<EOF | sed -e '/^Enter password:.*/ d';;
spawn -noecho sh -s -c "cat \\"$2\\" | mysql -B -u root -p \\"--default-character-set=$CSNAME\\" ${3:-}"
expect "*?assword:*" { send "$PASSWORD\\r" } eof { exit 1 }
expect { "*\n" { exp_continue } eof { exit } }
EOF
		*) fatal "Sorry, no support for \`$1' database yet.";;
	esac
}

# Checks if a database exists.
# args: db-type db-name
db_exists() {
	run_sql_cmd "$1" "show databases like '$2';" \
	| grep -q "^$2[[:space:]]*$"
}

# Set file owner group and mode.
# args: filename user group mode
chogm() {
	chown "$2" "$1"
	chgrp "$3" "$1"
	chmod "$4" "$1"
	[ "$4" = "0755" ] && chmod g-s "$1" || :
	verbose "Set $4 $2 $3 for $1"
}

# Sets the specified owner group and mode of a directory creating it
# optionally.
# args: dir user group mode
mmkfdir() {
	[ -d "$1" ] || mkdir "$1"
	chogm "$@"
}

# Creates the directory if it doesn't exist and sets its owner group
# and mode.
# args: dir user group mode
mmkdir() {
	if [ ! -d "$1" ]; then
		mkdir "$1"
		chogm "$@"
	fi
}

# Sets the specified owner group and mode of a file creating it
# optionally.
# args: filename user group mode
mmkffile() {
	[ -f "$1" ] || touch "$1"
	chogm "$@"
}

# Creates a file if it doesn't exist and sets its owner group
# and mode.
# args: filename user group mode
mmkfile() {
	if [ ! -f "$1" ]; then
		touch "$1"
		chogm "$@"
	fi
}

# Extracts the contents of the archive to the specified
# directory.
# args: target-dir
extract_to() {
	local target="$1"
	tar tzf "$CONFIGA" \
	| while read fn; do
		tfn="${target%/}/${fn%/}"
		case "$fn" in
			etc/zabbix/) mmkfdir "$tfn" root root 0755;;
			etc/zabbix/*) mmkffile "$tfn" root zabbix 0640;;
			var/www/) mmkfdir "$tfn" root webmaster 0755;;
			var/www/webapps/) mmkfdir "$tfn" root webmaster 2771;;
			var/www/webapps/zabbix/) mmkfdir "$tfn" apache2 root 0755;;
			var/www/webapps/zabbix/*/) mmkfdir "$tfn" apache2 root 0755;;
			var/www/webapps/zabbix/*) mmkffile "$tfn" apache2 apache2 0640;;
			var/lib/mysql/) mmkfdir "$tfn" root mysql 3771;;
			var/lib/mysql/tmp/) mmkfdir "$tfn" root mysql 7770;;
			var/lib/mysql/tmp/*) mmkffile "$tfn" mysql mysql 0644;;
			*/) mmkdir "$tfn" root root 0755;;
			*) mmkfile "$tfn" root root 0640;;
		esac
		if [ -f "$tfn" ]; then
			verbose "Output $tfn"
			tar xzOf "$CONFIGA" "$fn" > "$tfn"
		fi
	done
}

extract_to "$ROOT_DIR"

zbx_server() {
	"zabbix_$(read_metadata DBTYPE | tr [[:upper:]] [[:lower:]])" "$@"
}

# Gets the full path to an SQL script with the given name.
# args: script-base-name
get_script() {
	local base="${1:-}"
	[ -n "$base" ] && base="-$base"
	local script="$(read_metadata NAME)$base-$(read_metadata DBTYPE | tr [[:upper:]] [[:lower:]]).sql"
	echo "${ROOT_DIR%/}/$(tar tzf "$CONFIGA" | grep "\\(.*/\\)\\?$script$")"
}

apply_conf() {
	run_sql_script "$(read_metadata DBTYPE)" "$(get_script)"
	verbose "Recalculate DB for Id = $(read_metadata ID)"
	zbx_server -n "$(read_metadata ID)" -c "/etc/zabbix/zabbix_server.conf" || [ $? -eq 255 ]
	run_sql_script "$(read_metadata DBTYPE)" "$(get_script 'update')"
}

query_node_id() {
	run_sql_cmd "$(read_metadata DBTYPE)" \
		    "select nodeid from nodes where name='$(read_metadata NAME)' and ip='$(read_metadata DOWNLINK)';" \
		    "$(read_metadata DBNAME)" \
	| sed -n -e '/^[0-9]\+[[:space:]]*$/ {s/^\([0-9]\+\)[[:space:]]*$/\1/p; q}'
}

switch_to_conf() {
	local nodeid=
	# Try not to touch the DB
	verbose "Check if DB $(read_metadata DBNAME) exists"
	if db_exists "$(read_metadata DBTYPE)" "$(read_metadata DBNAME)"; then
		# Check the node Id
		verbose "Compare DB and configured node IDs"
		nodeid="$(query_node_id)"
		[ "$nodeid" = "$(read_metadata ID)" ] || fatal "Node IDs do not match (DB: $nodeid, conf: $(read_metadata ID)"
		verbose "Node IDs match -- node is ready"
	else
		verbose "Database $(read_metadata DBNAME) not found"
		apply_conf || fatal "Error while applying configuration"
	fi
}

case "$COMMAND" in
	apply) apply_conf || fatal "Error while applying configuration";;
	switch) switch_to_conf || fatal "Unable to switch to the configuration $(read_metadata NAME)";;
	*) fatal "Unrecognized command $COMMAND";;
esac
