#!/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
# zone -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:
. $PROGRAM_DIR/includes

# Built-in documentation:
function showdocs {
	$CAT <<-EODOC
		Add / remove zone (generally a domain) for an account in clonepanel system.
		Inputs may be given as command line parameters or interactively.
		Usage:
		1. List zones already defined:
		./zone -u myaccount
		2. Add / delete a zone from the list:
		./zone -z mydomain -u myaccount add|del
		Command line options: 
		-h		Print these instructions and exit
		-z mydomain	Domain / zone name
		-u myaccount	CPanel username of the account
		
EODOC
	exit $DOC_REQUEST
}

# Get zone(s) based on user input zone / domain name
function get_zone {
	n_matches=0
	if [ "$zone" ]; then
		matches=`$FIND $ZONES_DIR -maxdepth 1 -mindepth 1 -type d -name $zone -printf "%f "`
	else
		matches=`$FIND $ZONES_DIR -maxdepth 1 -mindepth 1 -type d -printf "%f "`
	fi
	if [ ! "$matches" ]; then
		return
	fi
	n_matches=`$ECHO $matches |$WC -w`
}

function create_zone {
	config -u $user -z $zone

	if [ ! -d "$ZONE_DIR" ] ; then
		create_dir $ZONE_DIR
	fi

	$CP $ZONE_TEMPLATE_DIR/* $ZONE_DIR/
# copy template / skeleton files to new zone directory
}

function run_get_dns {
# After adding new zone, recommend fetching dns info from DNS_MASTER host
	cecho -c $warning "New zone requires current dns zone information."
	cecho -n -c $prompt "Fetch dns info from DNS_MASTER host? (y/n):"
	read response
	if [ "$response" == "y" ]; then
		$PROGRAM_DIR/get_dns -u $user -z $zone
	fi
}

function run_sync_setup {
# After making changes to database setup, recommend syncing these to remote hosts
	cecho -c $warning "Changes made must be synchronised with remote host(s)"
	cecho -n -c $prompt "Run sync program now? (y/n):"
	read response
	if [ "$response" == "y" ]; then
		$PROGRAM_DIR/sync_remote -u $user
	fi
}



# Initialise own input variables:
command=list
user=''
zone=''
force='n'

# Start real script

# Check for help request and input variables in the command line options:
while getopts ":hu:z:f" opt
do
	case $opt in
		h)	showdocs
			;;
		u)	user=$OPTARG
			;;
		z)	zone=$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

if [ ! $user ]; then
	cecho -n -c $prompt "Enter CPanel account username: "
	read user
	if [ ! $user ]; then
		cecho -c $error "Account username must be specified"
		exit $E_BLANK_INPUTS
	fi
fi

config -u $user
# User-specific config options

if [ ! -d  $USER_DIR ]; then
	cecho -c $error "Error: No account with that username."
	exit $E_NO_ACCOUNT
fi

if [ ! -d "$ZONES_DIR" ] ; then
	create_dir $ZONES_DIR
fi

case $command in
	list)
		cecho -c $ok "Zones listed for $user:"
		get_zone

		if [ $n_matches -gt 0 ]; then
			for zonename in $matches
			do
				if [ -f $ZONES_DIR/$zonename/$ROLES_FILENAME ]; then
					cecho -c $info "Zone $zonename (custom roles):"
					$CAT $ZONES_DIR/$zonename/$ROLES_FILENAME
				else
					cecho -c $info "Zone $zonename (standard roles):"
					$CAT $ROLES_FILE
				fi
			done
			cecho -c $ok "$n_matches zone(s) listed"
		else
			cecho -c $warning "No matching zones"
		fi
		;;
	add)
		if [ ! $zone ]; then
			cecho -n -c $prompt "Enter zone / domain name: "
			read zone
			if [ ! $zone ]; then
				cecho -c $error "Zone / domain name must be specified"
				exit $E_BLANK_INPUTS
			fi
		fi
		get_zone
		case $n_matches in
			1)
				if [ $force != 'y' ]; then
					cecho -n -c $prompt "One matching zone exists - replace it (y/n)?: "
					read force
				fi
				;;
			0)
				;;
			*)
				if [ $force != 'y' ]; then
					cecho -n -c $prompt "$n_matches matching zones exist - delete all (y/n)?: "
					read force
				fi
				;;
		esac
		if [ $n_matches -gt 0 ]; then
			if [ $force == 'y' ]; then
				for match in $matches
				do
					$RM -rf $ZONES_DIR/$match
					checkerror $? $E_DELETE_ZONE_FAILED
					cecho -c $info "Zone $match deleted"
				done
			else 
				cecho -c $error "Aborted"
				exit $USER_ABORT
			fi
		fi
		
		create_zone
		run_get_dns
		run_sync_setup
		;;
	del)
		get_zone
		case $n_matches in
			0)
				cecho -c $error "No matching zones - nothing to delete"
				exit $E_ZONE_NOT_FOUND
				;;												
			1)
				$RM -rf $ZONES_DIR/$matches
				checkerror $? $E_DELETE_ZONE_FAILED
				;;
			*)
				if [ $force != 'y' ]; then
					cecho -n -c $prompt "$n_matches zones match your input - delete all (y/n)?: "
					read force
				fi
				if [ $force == 'y' ]; then
					for match in $matches
					do
						$RM -rf $ZONES_DIR/$match
						checkerror $? $E_DELETE_ZONE_FAILED
					done
				else 
					cecho -c $error "Aborted"
					exit $USER_ABORT
				fi
				;;
		esac
		run_sync_setup
		;;	
	*)	cecho -c $error "Unknown option. Use -h for instructions"; exit $E_UNKNOWN_OPT
		;;
esac



cecho -c $ok "Done!"













