#!/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
# setup - sets up paths, configuration options etc. All mods should be done
# in config files NOT HERE!


# First some empty definitions - LEAVE BLANK! These are to be set only
# on user- or host-specific config but need to be defined early to
# suppress unbound variable errors
USER_HOSTS_FILE_TP=''
REMOTEHOST_USERNAME=''
REMOTEHOST_HOME=''
WEB_MASTER=''
MAIL_MASTER=''
DNS_MASTER=''
SEND_MASTER=''
WEB_SLAVE=''
MAIL_SLAVE=''
DNS_SLAVE=''
SEND_SLAVE=''
# End of empty definitions

# Directories section - files / locations

ACCOUNTS_DIR=$SYNC_DIR/$ACCOUNTS_DIRNAME
TEMP_DIR=$SYNC_DIR/$TEMP_DIRNAME
TEMP_MONITOR_FILE=$TEMP_DIR/$TEMP_MONITOR_FILENAME
TEMP_SYNC_RES_FILE=$TEMP_DIR/$TEMP_SYNC_RES_FILENAME
SYSAUTH_DIR=$SYSTEM_DIR/$SYSAUTH_DIRNAME
REMOTE_SKEL=$TEMP_DIR/$REMOTE_SKELNAME

HOSTS_DIR=$SYNC_DIR/$HOSTS_DIRNAME
STATUS_FILE=$SYSTEM_DIR/$STATUS_FILENAME
UPDATES_FILE=$SYSTEM_DIR/$UPDATES_FILENAME
# ACCOUNTS_FILE=$SYSTEM_DIR/$ACCOUNTS_FILENAME
#HOST_NAME=$SYSTEM_DIR/$HOST_FILENAME

MONITOR_DIR=$SYSTEM_DIR/$MONITOR_DIRNAME
ERROR_LOG_DIR=$SYSTEM_DIR/$ERROR_LOG_DIRNAME
ERROR_IGNORE_FILE=$SYSTEM_DIR/$ERROR_IGNORE_FILENAME
REMOTE_SETUP_DIR=$SYNC_DIR/$REMOTE_SETUP_DIRNAME
REMOTE_PROGRAM_DIR=$REMOTE_SETUP_DIR/$REMOTE_PROGRAM_DIRNAME
REMOTE_CGI_DIR=$REMOTE_SETUP_DIR/$REMOTE_CGI_DIRNAME
LOCAL_DIR=$SYNC_DIR/$LOCAL_DIRNAME
# Path to directory of files destined for user's local account
LOCAL_SKEL=$LOCAL_DIR/$LOCAL_SKELNAME
# Path to skeleton directory of files to be used in user's local account
ZONE_TEMPLATE_DIR=$LOCAL_DIR/$ZONE_TEMPLATE_DIRNAME
# Directory containing skeleton zone files
PENDING_TASKS_DIR=$SYSTEM_DIR/$PENDING_TASKS_DIRNAME
# Directory containing pending tasks (DNS updates)

CRONTAB_TMP=$TEMP_DIR/$CRONTAB_TEMP_FILENAME
# Temporary file to hold crontab data

STATUS_TMP=$TEMP_DIR/$STATUS_TMP_FILENAME
# Temporary file to hold crontab data

# Now for some common functions to set up other config:

function config {
# Handle configuration specific to user, host, transfer type and zone
#Defaults:
        cf_host=''
        cf_user=''
        cf_type=''
	cf_zone=''
# Read options
        while getopts ":H:u:t:z:" opt
        do
                case $opt in
			H)	cf_host=$OPTARG
				;;
			u)	cf_user=$OPTARG
				;;
			t)	cf_type=$OPTARG
				;;
			z)	cf_zone=$OPTARG
				;;
			*)      $ECHO "Error - config syntax"
				exit 1
				;;
                esac
        done
        shift $(($OPTIND - 1))
        OPTIND=1
        # reset getopts for next time

	if [ "$cf_user" ]; then
# User setup -u username [-t WEB|MAIL]
		USERNAME=$cf_user
		REMOTEHOST_USERNAME=$USERNAME
# Default username for remote login
		USER_DIR=$ACCOUNTS_DIR/$cf_user
		AUTH_DIR=$USER_DIR/$AUTH_DIRNAME
# Directory storing access keys for hosts
		ROLES_FILE=$USER_DIR/$ROLES_FILENAME
# Defines which server is master and which is slave
		if [ -f $ROLES_FILE ]; then
			. $ROLES_FILE
		fi
# Standard roles file may be overridden later if zone is given
		ZONES_DIR=$USER_DIR/$ZONES_DIRNAME
# Directory containing all domains / zones owned by an account
		USER_HOSTS_FILE_TP=$USER_DIR/_HOST_/config
# Optional extra config file overrides standard host config for this user
		CRONJOB_DIR=$USER_DIR/$CRONJOB_DIRNAME
# (obselete?) directory in userdir where cron-job info held
		xtra_config_file=$USER_DIR/config
		if [ -f $xtra_config_file ]; then
			. $xtra_config_file
# override any standard config for specific user in this file, if it exists
		fi

		SNAPSHOT_DIR=$USER_DIR/$SNAPSHOT_DIRNAME
# Generic snapshot dir
		if [ "$cf_type" ]; then
			SNAPSHOT_SUBDIR=$SNAPSHOT_DIR/$cf_type;
# Directory for WEB or MAIL snapshots (optional -t param)
		fi
	fi
# end of user setup

	if [ "$cf_host" ]; then
# Host setup -H HOSTNAME

		HOSTS_FILE=$HOSTS_DIR/$cf_host/$HOSTS_CONFIG_FILENAME
# Configuration info for this host
		if [ ! -f $HOSTS_FILE ]; then
			cecho -c $error "Error - host config not found"
			exit $E_NO_HOST
		fi
		. $HOSTS_FILE

		if [ "$USER_HOSTS_FILE_TP" ]; then
# User-specific host setup (only defined during user setup above)
			USER_HOSTS_FILE=$($ECHO $USER_HOSTS_FILE_TP | $SED -e "s/_HOST_/$cf_host/")
			if [ -f "$USER_HOSTS_FILE" ]; then
# Configuration options specific to host and user (normally not required)
# Typically used to set $REMOTEHOST_USERNAME and $MIRROR_DIRS on non-CPanel hosts
		        	. $USER_HOSTS_FILE
			fi
		fi
		REMOTEHOST_HOME=$($ECHO $REMOTEHOST_HOME_TP |$SED -e "s/_USERNAME_/$REMOTEHOST_USERNAME/")
# Finally, set the correct username in the remotehost_home directory entry
# (default in main config, override in the included file hosts/HOSTNAME/config)
		REMOTEHOST_SYNC_DIR=$REMOTEHOST_HOME/$REMOTEHOST_SYNC_DIRNAME
		REMOTEHOST_PROGRAM_DIR=$REMOTEHOST_SYNC_DIR/$REMOTE_PROGRAM_DIRNAME
# And corresponding main clonepanel and program directories on remote host
		REMOTEHOST_ROLES_FILE=$REMOTEHOST_SYNC_DIR/$ROLES_FILENAME
# Roles file indicates role of each host
		REMOTEHOST_DATABASE_DIR=$REMOTEHOST_SYNC_DIR/$DATABASE_DIRNAME
		REMOTEHOST_DATABASE_STORE=$REMOTEHOST_HOME/$DATABASE_STORENAME
# database dir holds login information for the databases, database store holds sql dumps
		REMOTEHOST_MAIL_DIR=$REMOTEHOST_HOME/$MAIL_DIRNAME
		REMOTEHOST_CLONE_MAIL_DIR=$REMOTEHOST_HOME/$MAIL_CLONE_DIRNAME
# mail dir for access to mailboxes, clone mail dir for temporary duplicates
		REMOTEHOST_HOSTS_DIR=$REMOTEHOST_SYNC_DIR/$HOSTS_DIRNAME
# monitor hosts only - location of host data
	fi
	
	if [ "$cf_user" -a "$cf_zone" ]; then
# config specific to a single zone / domain
		ZONE_DIR=$ZONES_DIR/$cf_zone
# Directory for a single domain / zone
		xtra_config_file=$ZONE_DIR/config
		if [ -f $xtra_config_file ]; then
			. $xtra_config_file
# override any standard config for specific zone in this file, if it exists
		fi
		roles_file=$ZONE_DIR/$ROLES_FILENAME
		if [ -f $roles_file ]; then
			ROLES_FILE=$roles_file
			. $ROLES_FILE
# override and replace standard roles file with this one, if it exists
		fi
#		OVERRIDE_FILE=$ZONE_DIR/$OVERRIDE_FILENAME
# (obselete)
	fi
}


function create_dir {
	if [ ! "$1" ]; then
                cecho -c $error "Error - usage is create_dir <dirname>"
                exit $E_SYNTAX_ERROR
        fi
		
        cecho -c $info "Creating directory $1"
        $MKDIR $1
        checkerror $? $E_FAILED_CREATING_DIR
        if [ ! -d $1 ]; then
                cecho -c $error "Failed to create / open directory $1"
                exit $E_FAILED_OPENING_DIR
        fi
}
function addtocron {
# Add a new job to the crontab, unless there already
# addtocron command frequency [dummy]
# Optional 3rd parameter causes dummy run, printing crontab that would be used
	$CRONTAB -l |$GREP -v "$PROGRAM_DIR/$1" >$CRONTAB_TMP
	$ECHO "*/$2 * * * * $PROGRAM_DIR/$1" >>$CRONTAB_TMP
	dummy=''
	if [ $# -gt 2 ]; then
# Possible dummy run
		if [ "$3" != 'n' ]; then
			dummy='y'
		fi
	fi
	if [ "$dummy" ]; then
		cecho -c $info "Dummy run - crontab would be:"
		$CAT $CRONTAB_TMP
	else
		$CRONTAB $CRONTAB_TMP
		checkerror $? $E_WRITE_CRONTAB_FAILED
	fi
	# Rewrite crontab with this job added
}
function removefromcron {
# Remove job from the crontab
# removefromcron command
	$CRONTAB -l |$GREP -v "$PROGRAM_DIR/$1" >$CRONTAB_TMP
	$CRONTAB $CRONTAB_TMP
	checkerror $? $E_WRITE_CRONTAB_FAILED
}

# Check installation done
if [ ! "$MY_NAME" ]; then
        cecho -n -c $prompt "Clonepanel has not yet been installed. Run install now?[y] "
        read input
        if [ ! "$input" ]; then
		input=y
	fi
        if [ "$input" == "y" ]; then
		$PROGRAM_DIR/install
	fi
        exit
fi

# Host-specific Include files:
config -H $MY_NAME
MY_IP=$SERVER
# Get this server ip address
MY_A=$A
# Get this server A record
if [ ! "$MY_IP" -o ! "$MY_A" ]; then
        cecho -c $error "Bad config - this server not known / setup"
        exit $E_NO_THIS_HOST
fi

