#!/bin/sh

# ClonePanel - Manages duplicate accounts on two or more webservers,
# including snapshot backups, monitoring and failover dns.
# Copyright (C)2006 Chris Cheers, Internet Lynx.
# Contact chris[at]clonepanel[dot]com.
# Internet Lynx, PO Box 7117, Mannering Park, NSW 2259, Australia

# This program 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 Street, Fifth Floor, Boston, MA 02110-1301, USA.

Version=0.33
# server -h for built-in documentation

set -u
# Be strict about variable declaration

unset PATH
#avoid use of $PATH - limit script to system commands we choose

PROGRAM_DIR=$(/bin/echo $0 |/bin/sed -e "s/\/[a-zA-Z0-9_]*$//")
# Extract the working directory from command line
# NB - if your system doesn't have echo and sed in these locations
# then this line will need to be changed in all shell scripts

# Standard include files
# init suppresses setup - this script must be run before any host servers are defined
. $PROGRAM_DIR/includes init

HOSTS_DIR=$SYNC_DIR/$HOSTS_DIRNAME
STATUS_FILE=$SYSTEM_DIR/$STATUS_FILENAME
STATUS_TMP=$SYNC_DIR/$TEMP_DIRNAME/$STATUS_TMP_FILENAME
# Normally done in setup

# Built-in documentation:
function showdocs {
	$CAT <<-EODOC
		Add / remove host server from clonepanel system.
		Inputs may be given as command line parameters or interactively.
		Usage:
		1. List host servers already defined:
		./server [-H HOSTNAME]
		2. Add / delete a host server (specify options at prompts):
		./server add|delete
		3. Add / delete a host server (specify options on command line):
		./server -H HOSTNAME -a IP [-i IP -n IP -d WHM|BIND|NONE -o "VAR=value"] add|delete
		Command line options: 
		-h		Print these instructions and exit
		-c command	Command = add|delete|list
		-H HOSTNAME	Name (nickname) of new or existing host server
		-o VAR=value	Additional options (If in doubt leave these blank and enter when prompted). Examples:
		-o "server_a=12.34.56.78 server_port=22 server_ip=12.34.56.79"
		-o "nameserver_ip=12.34.56.80 dns_update=WHM"
		-o "monitor_ip=12.34.56.78 monitor_path=/cgi-bin/up.cgi monitor_domain=mydomain.com monitor_priority=1 monitor_location=AUS"
		-o "monitor_res_user=admin monitor_res_dir=public_html/monitor"
		-f		Force overwrite add or multiple delete
		
EODOC
	exit $DOC_REQUEST
}


function read_host_data {
	if [ ! "$server_ip" ]; then
		cecho -n -c $prompt "Enter server numeric IP address: "
		read server_ip
		if [ ! "$server_ip" ]; then
			cecho -c $error "Server IP address must be specified"
			exit $E_BLANK_INPUTS
		fi
	fi
	if [ ! "$server_a" ]; then
		cecho -n -c $prompt "Enter server A record [$server_ip]: "
		read server_a
		if [ ! "$server_a" ]; then
			server_a=$server_ip
		fi
	fi
	if [ ! "$server_port" ]; then
		cecho -n -c $prompt "Enter SSH port number [$SSH_PORT]: "
		read server_port
		if [ ! "$server_port" ]; then
			server_port=$SSH_PORT
		fi
	fi
	if [ ! "$nameserver_ip" ]; then
		cecho -n -c $prompt "Enter nameserver IP address (default blank): "
		read input
		if [ "$input" ]; then
			nameserver_ip=$input
		fi
	fi
	if [ "$nameserver_ip" -a "$dns_update" == "NONE" ]; then
		cecho -n -c $prompt "Enter dns update method [$dns_update]: "
		read input
		if [ "$input" ]; then
			dns_update=$input
		fi
	fi
	cecho -n -c $prompt "Enter template for home directory on this host server [$remotehost_home]: "
	read input
	if [ "$input" ]; then
		remotehost_home=$input
	fi

	if [ "$monitor_ip" == "NONE" ]; then
		cecho -n -c $prompt "Monitor this host server (y/n): "
		read input
		if [ "$input" == "y" ]; then
			read_monitor_data
		fi
	fi
	if [ ! "$monitor_res_user" ]; then
		cecho -n -c $prompt "Upload monitor data to this host server (y/n): "
		read input
		if [ "$input" == "y" ]; then
			read_monitor_result_data
		fi
	fi

}

function read_monitor_data {
	cecho -n -c $prompt "Enter monitor IP address [$server_a]: "
	read monitor_ip
	if [ ! "$monitor_ip" ]; then
		monitor_ip=$server_a
	fi
	cecho -n -c $prompt "Enter monitor path [$monitor_path]: "
	read input
	if [ "$input" ]; then
		monitor_path=$input
	fi
	if [ ! "$monitor_domain" ]; then
		monitor_domain=$monitor_ip
	fi
	cecho -n -c $prompt "Enter monitor domain name [$monitor_domain]: "
	read input
	if [ "$input" ]; then
		monitor_domain=$input
	fi
	cecho -n -c $prompt "Enter monitor priority [$monitor_priority]: "
	read input
	if [ "$input" ]; then
		monitor_priority=$input
	fi
	cecho -n -c $prompt "Will monitor act as proxy? [$monitor_proxy]: "
	read input
	if [ "$input" ]; then
		monitor_proxy=$input
	fi
	cecho -n -c $prompt "Enter server location [$monitor_location]: "
	read input
	if [ "$input" ]; then
		monitor_location=$input
	fi
	cecho -n -c $prompt "Extra e-mail for status change messages - SMS? [blank]: "
	read status_change_email
}

function read_monitor_result_data {
	cecho -n -c $prompt "Enter username for account to hold results files: "
	read monitor_res_user
	if [ ! "$monitor_res_user" ]; then
		cecho -c $error "Username must be specified"
		exit $E_BLANK_INPUTS
	fi
	cecho -n -c $prompt "Enter path to results file directory [$monitor_res_dir]: "
	read input
	if [ "$input" ]; then
		$monitor_res_dir=$input
	fi
}





function create_config_file {
	read_host_data

	cecho -c $info "Creating $HOSTS_DIR/$host/$HOSTS_CONFIG_FILENAME"

	$ECHO "$host=$STAT_DEFAULT" >> $STATUS_FILE
# Add host to status file

	if [ ! -d $HOSTS_DIR/$host ]; then
		$MKDIR $HOSTS_DIR/$host
		checkerror $? $E_MAKE_HOST_DIR_FAILED
	fi
	$CAT >$HOSTS_DIR/$host/$HOSTS_CONFIG_FILENAME << ENDDATA
SERVER='$server_ip'
SSH_PORT='$server_port'
NS='$nameserver_ip'
A='$server_a'
DNSUPDATE='$dns_update'
MONITOR_IP='$monitor_ip'
MONITOR_PATH='$monitor_path'
MONITOR_HOST='$monitor_domain'
PRIORITY=$monitor_priority
LOCATION='$monitor_location'
MONITOR_RESULT_USER='$monitor_res_user'
MONITOR_RESULT_DIR='$monitor_res_dir'
MONITOR_PROXY='$monitor_proxy'

REMOTEHOST_HOME='$remotehost_home'
STATUS_CHANGE_EMAIL='$status_change_email'

ENDDATA
}


# Initialise own input variables:
command=list
more_options=''

host=''
server_ip=''
nameserver_ip=''
server_a=''
server_port=''
dns_update='NONE'
force='n'
monitor_proxy='n'

monitor_ip='NONE'
monitor_path=cgi-bin/up.cgi
monitor_domain=''
monitor_priority=`$FIND $HOSTS_DIR -maxdepth 1 -mindepth 1 -type d |$WC -l`
monitor_location='USA'
status_change_email=''
monitor_res_user=''
monitor_res_dir=public_html/monitor

remotehost_home=/home/_USERNAME_


# Start real script

# Check for help request and input variables in the command line options:
while getopts ":hH:o:f:" opt
do
	case $opt in
		h)	showdocs
			;;
		H)	host=$OPTARG
			;;
		o)	more_options=$OPTARG
			;;
		f)	force='y'
			;;
		*)	$ECHO "Unknown option. Use -h for instructions"; exit $E_UNKNOWN_OPT
			;;
	esac
done
shift $(($OPTIND - 1))

OPTIND=1
# reset getopts for next time

if [ $# -gt 0 ]; then
	command=$1
fi

for opt in "$more_options"
do
	eval $opt
done
# Warning - insecure! Don't even think about connecting this up to a CGI program!

case $command in
	list)
		if [ "$host" ]; then
			if [ -d $HOSTS_DIR/$host ]; then
				hostlist=$host
			else
				cecho -c $error "No host found with that name"
				exit $E_NO_THIS_HOST
			fi
		else
			hostlist=`$FIND $HOSTS_DIR -maxdepth 1 -mindepth 1 -type d -printf "%f "`
			if [ ! "$hostlist" ]; then
				cecho -c $error "No host servers found"
				exit $E_NO_HOST
			fi
		fi
		for host in $hostlist
		do
			cecho -c $info "Settings for $host:"
			$CAT $HOSTS_DIR/$host/$HOSTS_CONFIG_FILENAME
			cecho
		done
		;;
	add)
		if [ ! $host ]; then
			cecho -n -c $prompt "Enter a name to use for this server: "
			read host
			if [ ! "$host" ]; then
				cecho -c $error "A name must be specified"
				exit $E_BLANK_INPUTS
			fi
		fi
		if [ -f $HOSTS_DIR/$host/$HOSTS_CONFIG_FILENAME ]; then
			if [ "$force" != "y" ]; then
				cecho -n -c $prompt "$host already exists. Overwrite it? y/n:"
				read response
				if [ "$response" != "y" ]; then
					cecho -c $error "No changes made"
					exit $USER_ABORT
				fi
			fi
		fi
		create_config_file
		$CAT $HOSTS_DIR/$host/$HOSTS_CONFIG_FILENAME

		;;
	del)
		if [ ! $host ]; then
			cecho -n -c $prompt "Enter a name to use for this server: "
			read host
			if [ ! "$host" ]; then
				cecho -c $error "A name must be specified"
				exit $E_BLANK_INPUTS
			fi
		fi
		$RM -rf $HOSTS_DIR/$host
		checkerror $? $E_REMOVE_HOST_DIR_FAILED
		$GREP -v "$host=" $STATUS_FILE >>$STATUS_TMP
		if [ $? -gt 1 ]; then
# Suppress error on grep returning 1 (error is 2)
			checkerror $? $E_REMOVE_HOST_STATUS_FAILED
		fi
		$MV $STATUS_TMP $STATUS_FILE
# Remove host from status file

#TODO - look for this host in accounts roles file and remove it










		;;
	*)	cecho -c $error "Unknown option. Use -h for instructions"; exit $E_UNKNOWN_OPT
		;;
esac



cecho -c $ok "Done!"













