#!/bin/bash
#version 0.9.0
#gedas@mc2.dev

### VARS ###
DEFAULTPACKAGE=NO-LIMIT
DNSMASTER="185.242.132.100"  # IP address of this server that should be used on the client host for multiserver
DNSSLAVE="193.178.43.30" # the second DNS server. This server should be able to login to DNSSLAVE via ssh
DNSSLAVEPORT="22" # port for dnsslave
ADMINUSER="admin" # server main admin user
TRUSTED_IPS="127.0.0.1,185.242.134.92,185.242.134.93,185.242.134.94,193.177.165.192,193.177.165.193,193.177.165.194,193.177.165.195,193.177.165.196" # comma separated list of IP addresses
### END VARS ###

######### FUNCTIONS

createUser() {

	#mandatory options:
	USERNAME="$1"
	PASSWORD="$2"
	DOMAIN="$3"

	if [[ -z "${USERNAME}" ]] || [[ -z "${PASSWORD}" ]] || [[ -z "${DOMAIN}" ]]; then
		echo "+---------------------------------------+"
		echo "Create a user:"
		echo "$0 createuser USERNAME PASSWORD DOMAIN <PACKAGE> <EMAIL>"
		echo "<PACKAGE> <EMAIL> are optional"
		echo "+---------------------------------------+"
		exit 1
	fi

	#optional
	PACKAGE="$4"
	EMAIL="$5"
	#default values if not set
	[[ -z "${PACKAGE}" ]] && PACKAGE="${DEFAULTPACKAGE}"
	[[ -z "${EMAIL}" ]] && EMAIL="admin@$(hostname -f)"

	#json template:
	CREATE_USER_JSON=$(cat <<- EOF
	{
		"username": "${USERNAME}",
		"email": "${EMAIL}",
		"passwd": "${PASSWORD}",
		"passwd2": "${PASSWORD}",
		"domain": "${DOMAIN}",
		"package": "${PACKAGE}",
		"ip": "server",
		"notify": "no",
		"json": "yes",
		"add": "yes",
		"action": "create"
	}
	EOF
	)
	#create user
	curl -k -X -u "$(/usr/local/directadmin/directadmin root-auth-url --user="${ADMINUSER}")/CMD_ACCOUNT_USER?json=yes" --request "POST" --data "${CREATE_USER_JSON}"
}

deleteUser() {

	USERNAME="$1"


	if [[ -z "${USERNAME}" ]]; then
		echo "+---------------------------------------+"
		echo "Delete a user:"
		echo "$0 deleteuser USERNAME"
		echo "+---------------------------------------+"
		exit 1
	fi

	DELETE_USER_JSON=$(cat <<- EOF
	{
		"leave_dns": "no",
		"json": "yes",
		"location": "CMD_ALL_USER_SHOW",
		"delete": "yes",
		"confirmed": "yes",
		"select0": "${USERNAME}"
	}
	EOF
	)
	curl -k -X -u "$(/usr/local/directadmin/directadmin root-auth-url --user="${ADMINUSER}")/CMD_SELECT_USERS?json=yes" --request "POST" --data "${DELETE_USER_JSON}"
}

createDB() {

	DBNAME="$1"
	DBUSERNAME="$2"
	DBPASSWORD="$3"

	if [[ -z "${DBNAME}" ]] || [[ -z "${DBUSERNAME}" ]] || [[ -z "${DBPASSWORD}" ]]; then
		echo "+---------------------------------------+"
		echo "Create a database:"
		echo "$0 createdb DBNAME DBUSERNAME DBPASSWORD"
		echo "+---------------------------------------+"
		exit 1
	fi

	USERNAME=$(echo "${DBNAME}" | cut -f1 -d_)
	DBNAME=$(echo "${DBNAME}" | cut -f2 -d_)
	DBUSERNAME=$(echo "${DBUSERNAME}" | cut -f2 -d_)

	CREATE_DB_JSON=$(cat <<- EOF
	{
		"name": "${DBNAME}",
		"user": "${DBUSERNAME}",
		"passwd": "${DBPASSWORD}",
		"passwd2": "${DBPASSWORD}",
		"userlist": "...",
		"json": "yes",
		"action": "create"
	}
	EOF
	)

	#create db
	curl -k -X -u "$(/usr/local/directadmin/directadmin root-auth-url --user="${USERNAME}")/CMD_DB?json=yes" --request "POST" --data "${CREATE_DB_JSON}"
}

deleteDB() {

	DBNAME="$1"

	if [[ -z "${DBNAME}" ]]; then
		echo "+---------------------------------------+"
		echo "Delete a database:"
		echo "$0 deletedb DBNAME"
		echo "+---------------------------------------+"
		exit 1
	fi

	USERNAME=$(echo "${DBNAME}" | cut -f1 -d_)

	DELETE_DB_JSON=$(cat <<- EOF
	{
		"json": "yes",
		"action": "select",
		"delete_db": "yes",
		"select0": "${DBNAME}"
	}
	EOF
	)

	curl -k -X -u "$(/usr/local/directadmin/directadmin root-auth-url --user="${USERNAME}")/CMD_DB?json=yes" --request "POST" --data "${DELETE_DB_JSON}"

}


createForwarder() {

	FORWARDER="$1"
	DESTINATION="$2"

	if [[ -z "${FORWARDER}" ]] || [[ -z "${DESTINATION}" ]]; then
		echo "+---------------------------------------+"
		echo "Create a forwarder:"
		echo "$0 createforwarder FORWARDER DESTINATION"
		echo "+---------------------------------------+"
		exit 1
	fi

	DOMAIN=$(echo "${FORWARDER}" | cut -f2 -d@)
	USERNAME=$(grep -E "^${DOMAIN}:" -m1 /etc/virtual/domainowners | cut -f2 -d: | xargs)

	CREATE_FORWARDER_JSON=$(cat <<- EOF
	{
		"json": "yes",
		"action": "create",
		"raw_forwarders": "${FORWARDER} --> ${DESTINATION}"
	}
	EOF
	)

	curl -k -X -u "$(/usr/local/directadmin/directadmin root-auth-url --user="${USERNAME}")/CMD_EMAIL_FORWARDER?json=yes" --request "POST" --data "${CREATE_FORWARDER_JSON}"
}


deleteForwarder() {

	FORWARDER="$1"

	if [[ -z "${FORWARDER}" ]]; then
		echo "+---------------------------------------+"
		echo "Delete a forwarder:"
		echo "$0 deleteforwarder FORWARDER"
		echo "+---------------------------------------+"
		exit 1
	fi

	DOMAIN=$(echo "${FORWARDER}" | cut -f2 -d@)
	BOX=$(echo "${FORWARDER}" | cut -f1 -d@)
	USERNAME=$(grep -E "^${DOMAIN}:" -m1 /etc/virtual/domainowners | cut -f2 -d: | xargs)

	DELETE_FORWARDER_JSON=$(cat <<- EOF
	{
		"domain": "${DOMAIN}",
		"json": "yes",
		"action": "delete",
		"delete": "yes",
		"select0": "${BOX}"
	}
	EOF
	)
	curl -k -X -u "$(/usr/local/directadmin/directadmin root-auth-url --user="${USERNAME}")/CMD_EMAIL_FORWARDER?json=yes" --request "POST" --data "${DELETE_FORWARDER_JSON}"
}

createDomain() {

	USERNAME="$1"
	DOMAIN="$2"

	if [[ -z "${USERNAME}" ]] || [[ -z "${DOMAIN}" ]]; then
		echo "+---------------------------------------+"
		echo "Create a domain for a user:"
		echo "$0 createdomain USERNAME DOMAIN"
		echo "or"
		echo "$0 createdomain USERNAME list=file"
		echo "+---------------------------------------+"
		exit 1
	fi


	if [[ $(echo "${DOMAIN}" | grep -c -E  "^list=") -gt 0 ]]; then
		DOMFILE=$(echo "${DOMAIN}" | cut -f2 -d=)
		for DOMAIN in $(cat "${DOMFILE}"); do
		   CREATE_DOMAIN_JSON=$(cat <<- EOF
		{
			"domain": "${DOMAIN}",
			"uquota": "unlimited",
			"ssl": "ON",
			"php": "ON",
			"json": "yes",
			"action": "create",
			"ubandwidth": "unlimited"
		}
		EOF
		)
			curl -k -X -u "$(/usr/local/directadmin/directadmin root-auth-url --user="${USERNAME}")/CMD_DOMAIN?json=yes" --request "POST" --data "${CREATE_DOMAIN_JSON}"
		done
	else
		CREATE_DOMAIN_JSON=$(cat <<- EOF
	{
		"domain": "${DOMAIN}",
		"uquota": "unlimited",
		"ssl": "ON",
		"php": "ON",
		"json": "yes",
		"action": "create",
		"ubandwidth": "unlimited"
	}
	EOF
	)
		curl -k -X -u "$(/usr/local/directadmin/directadmin root-auth-url --user="${USERNAME}")/CMD_DOMAIN?json=yes" --request "POST" --data "${CREATE_DOMAIN_JSON}"
	fi
}

 deleteDomain() {

	USERNAME="$1"
	DOMAIN="$2"

	if [[ -z "${USERNAME}" ]] || [[ -z "${DOMAIN}" ]]; then
		echo "+---------------------------------------+"
		echo "Delete a domain from a user:"
		echo "$0 deletedomain USERNAME DOMAIN"
		echo "or"
		echo "$0 deletedomain USERNAME list=file"
		echo "+---------------------------------------+"
		exit 1
	fi

	if [[ $(echo "${DOMAIN}" | grep -c -E  "^list=") -gt 0 ]]; then
		DOMFILE=$(echo "${DOMAIN}" | cut -f2 -d=)
		for DOMAIN in `cat "${DOMFILE}"`; do
			DELETE_DOMAIN_JSON=$(cat <<- EOF
			{
				"delete_data": "yes",
				"json": "yes",
				"action": "select",
				"delete": "yes",
				"confirmed": "yes",
				"delete_data_aware": "yes",
				"select0": "${DOMAIN}"
			}
			EOF
			)
			curl -k -X -u "$(/usr/local/directadmin/directadmin root-auth-url --user="${USERNAME}")/CMD_DOMAIN?json=yes" --request "POST" --data "${DELETE_DOMAIN_JSON}"
		done
	else
		DELETE_DOMAIN_JSON=$(cat <<- EOF
		{
			"delete_data": "yes",
			"json": "yes",
			"action": "select",
			"delete": "yes",
			"confirmed": "yes",
			"delete_data_aware": "yes",
			"select0": "${DOMAIN}"
		}
		EOF
		)
			curl -k -X -u "$(/usr/local/directadmin/directadmin root-auth-url --user="${USERNAME}")/CMD_DOMAIN?json=yes" --request "POST" --data "${DELETE_DOMAIN_JSON}"
	fi

 }

enableSSH() {

	USERNAME="$1"

	if [[ -z "${USERNAME}" ]]; then
		echo "+---------------------------------------+"
		echo "Enable SSH for a user:"
		echo "$0 enablessh USERNAME"
		echo "+---------------------------------------+"
		exit 1
	fi

	chsh -s /bin/bash "${USERNAME}"
	sed -i -e 's/ssh=OFF/ssh=ON/g' /usr/local/directadmin/data/users/"${USERNAME}"/user.conf

 }

disableSSH() {

	USERNAME="$1"

	if [[ -z "${USERNAME}" ]]; then
		echo "+---------------------------------------+"
		echo "Disable SSH for a user:"
		echo "$0 disablessh USERNAME"
		echo "+---------------------------------------+"
		exit 1
	fi

	chsh -s /bin/false "${USERNAME}"
	sed -i -e 's/ssh=ON/ssh=OFF/g' /usr/local/directadmin/data/users/"${USERNAME}"/user.conf
}

docroot() {


	USERNAME="$1"
	DOMAIN="$2"
	DOCROOT="$3"

	if [[ -z "${USERNAME}" ]] || [[ -z "${DOMAIN}" ]] || [[ -z "${DOCROOT}" ]]; then
		echo "+---------------------------------------+"
		echo "Change DOCROOT for a domain:"
		echo "$0 docroot USERNAME DOMAIN DOCROOT"
		echo "Example $0 docroot john domain.tld domains/domain.tld/public_html"
		echo "+---------------------------------------+"
		exit 1
	fi

	if [[ $(grep DOCROOT "/usr/local/directadmin/data/users/${USERNAME}/domains/${DOMAIN}.cust_httpd" -q -c) -gt 0 ]]; then
		echo "Custom docroot already exist. Please remove the customisation."
	else
		echo "|?DOCROOT=/home/${USERNAME}/${DOCROOT}|" >> "/usr/local/directadmin/data/users/${USERNAME}/domains/${DOMAIN}.cust_httpd"
		echo "action=rewrite&value=httpd&domain=${DOMAIN}" >> /usr/local/directadmin/data/task.queue.cb
		/usr/local/directadmin/dataskq d --custombuild
	fi
 }

createmailbox() {

	DOMAIN="$1"
	MBOX="$2"
	PASSWORD="$3"
	SIZE="$4"
	[[ -z "${SIZE}" ]] && SIZE="0"

	local JSON_DATA
	JSON_DATA=$(cat <<- EOF
	{
		"user": "${MBOX}",
		"passwd2": "${PASSWORD}",
		"passwd": "${PASSWORD}",
		"quota": "${SIZE}",
		"limit": "200",
		"domain": "${DOMAIN}",
		"json": "yes",
		"action": "create"
	}
	EOF
	)

	USERNAME=$(grep -E "^${DOMAIN}:" -m1 /etc/virtual/domainowners | cut -f2 -d: | xargs)

	curl -k -X -u "$(/usr/local/directadmin/directadmin root-auth-url --user="${USERNAME}")/CMD_EMAIL_POP?json=yes" --request "POST" --data "${JSON_DATA}"
}

createmail() {

	if [[ -n "$1" ]] && [[ -n "$2" ]] && [[ -n "$3" ]]; then
		createmailbox "$1" "$2" "$3" "$4"
	elif [[ -n "$1" ]] &&  [[ -z "$2" ]]; then
		echo "Importing mailboxes from file: $1"
		if [ ! -f "$1" ]; then 
			echo "File $1 doesn't exist"
			exit 1
		fi
		while IFS= read -r line; do
			[[ -z "${line}" ]] && continue
			echo; echo
			mbox=$(echo "${line}" | awk '{print $1}' | cut -f1 -d@)
			domain=$(echo "${line}" | awk '{print $1}' | cut -f2 -d@)
			echo "Mailbox: ${mbox}@${domain}"
			password=$(echo "${line}" | awk '{print $2}')
			if [ -z "${password}" ]; then
				echo "Missing password for ${mbox}@${domain} - skipping"
				continue;
			fi
			size=$(echo "${line}" | awk '{print $3}')
			createmailbox "${domain}" "${mbox}" "${password}" "${size}"
		done < "$1"
			
	else 
		echo "+---------------------------------------+"
		echo "Create a mailbox:"
		echo "$0 createmail DOMAIN MBOX PASSWORD <SIZE>"
		echo "$0 createmail FILENAME"
		echo "+---------------------------------------+"
		exit 1
	fi


}

deletemail() {

	DOMAIN="$1"
	MBOX="$2"


	if [[ -z "${DOMAIN}" ]] || [[ -z "${MBOX}" ]]; then
		echo "+---------------------------------------+"
		echo "Delete a mailbox:"
		echo "$0 deletemail DOMAIN MBOX"
		echo "+---------------------------------------+"
		exit 1
	fi

	DELETE_EMAIL_JSON=$(cat <<- EOF
	{
		"clean_forwarders": "yes",
		"domain": "${DOMAIN}",
		"json": "yes",
		"action": "delete",
		"delete": "yes",
		"select0": "${MBOX}"
	}
	EOF
	)

	USERNAME=$(grep -E "^${DOMAIN}:" -m1 /etc/virtual/domainowners | cut -f2 -d: | xargs)

	curl -k -X -u "$(/usr/local/directadmin/directadmin root-auth-url --user="${USERNAME}")/CMD_EMAIL_POP?json=yes" --request "POST" --data "${DELETE_EMAIL_JSON}"
}

enabledkim() {
	DOMAIN="$1"

	if [[ -z "${DOMAIN}" ]]; then
		echo "+---------------------------------------+"
		echo "Enable DKIM for a domain:"
		echo "$0 enabledkim DOMAIN"
		echo "+---------------------------------------+"
		exit 1
	fi

	ENABLE_DKIM_JSON=$(cat <<- EOF
	{
		"action": "set_dkim",
		"domain": "${DOMAIN}",
		"json": "yes",
		"enable": "yes"
	}
	EOF
	)

	USERNAME=$(grep -E "^${DOMAIN}:" -m1 /etc/virtual/domainowners | cut -f2 -d: | xargs)

	curl -k -X -u "$(/usr/local/directadmin/directadmin root-auth-url --user="${USERNAME}")/CMD_EMAIL_POP?json=yes" --request "POST" --data "${ENABLE_DKIM_JSON}"

}

disabledkim() {
	DOMAIN="$1"

	if [[ -z "${DOMAIN}" ]]; then
		echo "+---------------------------------------+"
		echo "Enable DKIM for a domain:"
		echo "$0 enabledkim DOMAIN"
		echo "+---------------------------------------+"
		exit 1
	fi

	DISABLE_DKIM_JSON=$(cat <<- EOF
	{
		"action": "set_dkim",
		"domain": "${DOMAIN}",
		"json": "yes",
		"disable": "yes"
	}
	EOF
	)

	USERNAME=$(grep -E "^${DOMAIN}:" -m1 /etc/virtual/domainowners | cut -f2 -d: | xargs)

	curl -k -X -u "$(/usr/local/directadmin/directadmin root-auth-url --user="${USERNAME}")/CMD_EMAIL_POP?json=yes" --request "POST" --data "${DISABLE_DKIM_JSON}"
}

changemailpass() {

	DOMAIN="$1"
	MBOX="$2"
	PASSWORD="$3"

	if [[ -z "${DOMAIN}" ]] || [[ -z "${MBOX}" ]] || [[ -z "${PASSWORD}" ]]; then
		echo "+---------------------------------------+"
		echo "Change mailbox password:"
		echo "$0 changemailpass DOMAIN MBOX PASSWORD"
		echo "+---------------------------------------+"
		exit 1
	fi

	CHANGE_EMAIL_PASS_JSON=$(cat <<- EOF
	{
		"user": "${MBOX}",
		"newuser": "${MBOX}",
		"passwd2": "${PASSWORD}",
		"passwd": "${PASSWORD}",
		"quota": "50",
		"limit": "200",
		"domain": "${DOMAIN}",
		"json": "yes",
		"action": "modify"
	}
	EOF
	)

	USERNAME=$(grep -E "^${DOMAIN}:" -m1 /etc/virtual/domainowners | cut -f2 -d: | xargs)

	curl -k -X -u "$(/usr/local/directadmin/directadmin root-auth-url --user="${USERNAME}")/CMD_EMAIL_POP?json=yes" --request "POST" --data "${CHANGE_EMAIL_PASS_JSON}"
}

changeuserpass() {

	USER="$1"
	PASSWORD="$2"

	if [[ -z "${USER}" ]] || [[ -z "${PASSWORD}" ]]; then
		echo "+---------------------------------------+"
		echo "Change mailbox password:"
		echo "$0 changeuserpass LOGIN PASSWORD"
		echo "+---------------------------------------+"
		exit 1
	fi

	CHANGE_USER_PASS_JSON=$(cat <<- EOF
	{
		"username": "${USER}",
		"passwd": "${PASSWORD}",
		"json": "yes",
		"action": "create",
		"referer": "CMD_API_USER_PASSWD",
		"passwd2": "${PASSWORD}"
	}
	EOF
	)

	curl -k -X -u "$(/usr/local/directadmin/directadmin root-auth-url --user="${ADMINUSER}")/CMD_USER_PASSWD?json=yes" --request "POST" --data "${CHANGE_USER_PASS_JSON}"
}

disablenamed() {
	sed -i -e 's/named=ON/named=OFF/g' /usr/local/directadmin/data/admin/services.status
	systemctl stop named
	systemctl disable named

	NAMED_PLACEBO=$(cat <<- EOF
		[Unit]
		Description=Named Placebo
		After=syslog.target network.target
		Requires=network.target
		Documentation=http://help.directadmin.com/item.php?id=25

		[Service]
		Type=oneshot
		ExecStart=/usr/bin/echo -n ''
		EOF
		)

	[[ -f '/etc/systemd/system/named.service' ]] && echo "${NAMED_PLACEBO}" > /etc/systemd/system/named.service
	[[ -f '/usr/lib/systemd/system/named.service' ]] && echo "${NAMED_PLACEBO}" > /usr/lib/systemd/system/named.service

	systemctl daemon-reload
}

enablenamed() {
	[[ $(grep -q 'Placebo' /etc/systemd/system/named.service) ]] && rm -fv /etc/systemd/system/named.service
	[[ $(grep -q 'Placebo' /usr/lib/systemd/system/named.service) ]] && rm -fv /usr/lib/systemd/system/named.service

	cd /usr/local/directadmin/custombuild || exit 1
	./build update
	./build bind
}

sethostname() {
	/usr/local/directadmin/scripts/hostname.sh "$1"
}

multiserver() {
	#Is used to create admin account locally + create the same account on the DNSSLAVE server using SSH.
	#Then client to the CLIENTHOSTNAME and use that for multiserver setup.

	CLIENTNAME="$2"

	if [[ $(echo "$1" | grep ':' -c) -eq 1 ]]; then
	CLIENTHOSTPORT=$(echo "$1" | cut -f2 -d:)
	CLIENTHOSTNAME=$(echo "$1" | cut -f1 -d:)
	else
		CLIENTHOSTNAME="$1"
	CLIENTHOSTPORT="22"
	fi

	if [[ -z "${CLIENTHOSTNAME}" ]] || [[ -z "${CLIENTNAME}" ]]; then
		echo "+---------------------------------------+"
		echo "Push multiserver settings to CLIENTHOSTNAME:"
		echo "$0 multiserver CLIENTHOSTNAME CLIENTNAME"
		echo "+---------------------------------------+"
		exit 1
	fi


	GLOBALKEYDIR="/usr/local/directadmin/data/users/admin/login_keys"
	KEYDIR="${GLOBALKEYDIR}/dns${CLIENTNAME}"
	PASSWD=`openssl rand -base64 20`
	HASH=`printf "%s\n%s\n" "$PASSWD" "$PASSWD" | doveadm pw -s SHA512-CRYPT | grep -o '$6$.*'`

## precheck connectivity

	if [[ `whoami` == root ]]; then
		if [[ `ssh -lroot ${CLIENTHOSTNAME} -p ${CLIENTHOSTPORT} 'whoami'` == "root" ]]; then
			if [[ `ssh -lroot ${DNSSLAVE} -p ${DNSSLAVEPORT} 'whoami'` == "root" ]]; then
				echo "Access looks good"
			else
				echo "Error: We need root access to the ${DNSSLAVE}"
				exit 1
			fi
		else
			echo "Error: We need root access to the ${CLIENTHOSTNAME}"
			exit 1
		fi
	else
		echo "Error: Script must be executed as root"
		exit 1
	fi

## local DNS key creation
	echo "Creating local keys 'dns${CLIENTNAME}'"
	mkdir -p "${KEYDIR}"

	cat <<- EOF > "${KEYDIR}/key.conf"
		allow_htm=no
		clear_key=no
		created_by=127.0.0.1
		date_created=$(date +%s)
		expiry=0
		key=${HASH}
		max_uses=0
		uses=0
		EOF

	cat <<- EOF > "${KEYDIR}/commands.allow"
		CMD_API_DNS_ADMIN
		CMD_API_LOGIN_TEST
		EOF

	chown -R diradmin:diradmin "${KEYDIR}"
	chmod 700 "${KEYDIR}"
	chmod 600 "${KEYDIR}/key.conf" "${KEYDIR}/commands.allow"

	## Remote DNS rsync keys to DNSSLAVE.
	echo "Syncing keys to ${DNSSLAVE}"
	rsync ${KEYDIR}/ root@${DNSSLAVE}:${KEYDIR}/ -e "ssh -p ${DNSSLAVEPORT}" -a --delete

	### Push settings to the client server.
	echo "Enabling multiserver on the ${CLIENTHOSTNAME}:${CLIENTHOSTPORT}"
	BASE64PW=$(echo -n "${PASSWD}" | base64)
	SSHREMOTE="ssh -lroot ${CLIENTHOSTNAME} -p${CLIENTHOSTPORT} --"
	CLUSTERCONF="/usr/local/directadmin/data/admin/cluster.conf"

	${SSHREMOTE} "/usr/local/directadmin/directadmin set cluster 1"
	${SSHREMOTE} "systemctl restart directadmin"
	${SSHREMOTE} "touch ${CLUSTERCONF}"
	${SSHREMOTE} "chown diradmin:diradmin ${CLUSTERCONF}"
	${SSHREMOTE} "chmod 600 ${CLUSTERCONF}"
	${SSHREMOTE} "sed -i -e '/^${DNSMASTER}=/d' ${CLUSTERCONF}"
	${SSHREMOTE} "sed -i -e '/^${DNSSLAVE}=/d' ${CLUSTERCONF}"
	${SSHREMOTE} "echo '${DNSMASTER}=dns=yes&domain_check=yes&email=no&passwd=${BASE64PW}&port=2222&show_all_users=no&ssl=${CLUSTERSSL}&user=admin&user_check=no&user_sync=no' >> ${CLUSTERCONF}"
	${SSHREMOTE} "echo '${DNSSLAVE}=dns=yes&domain_check=yes&email=no&passwd=${BASE64PW}&port=2222&show_all_users=no&ssl=${CLUSTERSSL}&user=admin&user_check=no&user_sync=no'  >> ${CLUSTERCONF}"
	${SSHREMOTE} "echo 'action=rewrite&value=named' >> /usr/local/directadmin/data/task.queue; /usr/local/directadmin/dataskq d"

}

enablemultiserver() {

	ENABLE_MULTISERVER_JSON=$(cat <<- EOF
	{
		"json": "yes",
		"action": "onoff",
		"on": "yes"
	}
	EOF
	)

	curl -k -X -u "$(/usr/local/directadmin/directadmin root-auth-url --user="${ADMINUSER}")/CMD_MULTI_SERVER?json=yes" --request "POST" --data "${ENABLE_MULTISERVER_JSON}"

}

disablemultiserver() {

	DISABLE_MULTISERVER_JSON=$(cat <<- EOF
	{
		"json": "yes",
		"action": "onoff",
		"off": "yes"
	}
	EOF
	)

	curl -k -X -u "$(/usr/local/directadmin/directadmin root-auth-url --user="${ADMINUSER}")/CMD_MULTI_SERVER?json=yes" --request "POST" --data "${DISABLE_MULTISERVER_JSON}"

}


enablemultiserverpage() {
	ALL_PRE="/usr/local/directadmin/scripts/custom/all_pre.sh"

	if [[ -f "${ALL_PRE}" ]] && [[ $(grep -m1 '###########DISABLEMULTISERVER#########' "${ALL_PRE}") ]]; then
		perl -i -0pe 's/###########DISABLEMULTISERVER.*DISABLEMULTISERVEREND#########//gs' "${ALL_PRE}"
		echo "Multiserver page has been enabled"
	else
		echo "Multiserver page is not disabled. Not doing anything"
	fi

}

disablemultiserverpage() {
	ALL_PRE="/usr/local/directadmin/scripts/custom/all_pre.sh"
	ALLOW_LIST="/usr/local/directadmin/scripts/custom/admin_allow.list"

	if [[ -f "${ALL_PRE}" ]] && [[ `grep -m1 '###########DISABLEMULTISERVER#########' "${ALL_PRE}"` ]]; then
		echo "Seems like multiserver page is already disabled"
		exit 0
	fi
	echo "Creating admin whitelist IP file."
	echo "${TRUSTED_IPS}" | sed -e "s/,/\n/g" > "${ALLOW_LIST}"


	DISABLE_ADMIN=$(cat <<- EOF
		#!/bin/sh
		###########DISABLEMULTISERVER#########
		if [ "\$command" = "/CMD_API_MULTI_SERVER" ]; then
			if grep -m1 -q "^\$caller_ip$" "${ALLOW_LIST}"; then
			exit 0;
			fi
			echo "You cannot use multiserver";
			exit 1;
		fi
		if [ "\$command" = "/CMD_MULTI_SERVER" ]; then
			if grep -m1 -q "^\$caller_ip$" "${ALLOW_LIST}"; then
			exit 0;
			fi
			echo "You cannot use multiserver";
			exit 1;
		fi
		###########DISABLEMULTISERVEREND#########
		EOF
		)
	echo "Adding disable script"
	echo "${DISABLE_ADMIN}" > "${ALL_PRE}.tmp"
	chown diradmin:diradmin "${ALL_PRE}.tmp" "${ALLOW_LIST}"
	chmod 700 "${ALL_PRE}.tmp" "${ALLOW_LIST}"
	if [[ -f "${ALL_PRE}" ]]; then
		tail -n+2 "${ALL_PRE}" >> "${ALL_PRE}.tmp"
	fi
	mv -f "${ALL_PRE}.tmp" "${ALL_PRE}"
	echo "Done"
}


enablecreateadmin() {
	ALL_PRE="/usr/local/directadmin/scripts/custom/all_pre.sh"

	if [[ -f "${ALL_PRE}" ]] && [[ `grep -m1 '###########DISABLEADMIN#########' "${ALL_PRE}"` ]]; then
		perl -i -0pe 's/###########DISABLEADMIN.*DISABLEADMINEND#########//gs' "${ALL_PRE}"
		echo "Admin creation has been enabled"
	else
		echo "Admin creation is not disabled. Not doing anything"
	fi

}

disablecreateadmin() {
	ALL_PRE="/usr/local/directadmin/scripts/custom/all_pre.sh"
	ALLOW_LIST="/usr/local/directadmin/scripts/custom/admin_allow.list"

	if [[ -f "${ALL_PRE}" ]] && [[ `grep -m1 '###########DISABLEADMIN#########' "${ALL_PRE}"` ]]; then
		echo "Seems like admin creation is already disabled"
		exit 0
	fi
	echo "Creating admin whitelist IP file."
	echo "${TRUSTED_IPS}" | sed -e "s/,/\n/g" > "${ALLOW_LIST}"


	DISABLE_ADMIN=$(cat <<- EOF
		#!/bin/sh
		###########DISABLEADMIN#########
		if [ "\$command" = "/CMD_API_ACCOUNT_ADMIN" ]; then
			if grep -m1 -q "^\$caller_ip$" "${ALLOW_LIST}"; then
			exit 0;
			fi
			echo "You cannot create admin";
			exit 1;
		fi
		if [ "\$command" = "/CMD_ACCOUNT_ADMIN" ]; then
			if grep -m1 -q "^\$caller_ip$" "${ALLOW_LIST}"; then
			exit 0;
			fi
			echo "You cannot create admin";
			exit 1;
		fi
		###########DISABLEADMINEND#########
		EOF
		)
	echo "Adding disable script"
	echo "${DISABLE_ADMIN}" > "${ALL_PRE}.tmp"
	chown diradmin:diradmin "${ALL_PRE}.tmp" "${ALLOW_LIST}"
	chmod 700 "${ALL_PRE}.tmp" "${ALLOW_LIST}"
	if [[ -f "${ALL_PRE}" ]]; then
		tail -n+2 "${ALL_PRE}" >> "${ALL_PRE}.tmp"
	fi
	mv -f "${ALL_PRE}.tmp" "${ALL_PRE}"
	echo "Done"
}

phpCommands () {
	if [[ "$1" == "list" ]]; then
		phpList 0 "$2"
	elif [[ "$1" == "set" ]]; then
		phpSet "$2" "$3"
	elif [[ "$1" == "export" ]]; then
		phpExport "$2" "$3"
	elif [[ "$1" == "import" ]]; then
		phpImport "$2"
	else
		echo "Wrong options!"
		exit 1
	fi
}

phpList () {
	CBOPTIONS="/usr/local/directadmin/custombuild/options.conf"
	USERSDATA="/usr/local/directadmin/data/users"
	EXPORT=$1

	OSRELEASE="/etc/os-release"
	if [[ -f "${OSRELEASE}" ]]; then
		OSNAME=$(grep -E "^NAME=" "${OSRELEASE}" | cut -f2 -d= | tr -cd '[:alnum:]')
		if [[ ${OSNAME} == "CloudLinux" ]]; then
			if [[ ${EXPORT} -eq 0 ]]; then
				echo "Cloudlinux detected"
			fi
			if [[ $(/usr/sbin/cagefsctl --cagefs-status 2> /dev/null) == "Enabled" ]]; then
				CL=1
			else
				if [[ ${EXPORT} -eq 0 ]]; then
					echo "But cagefs is disabled. CL selector is not acitve"
				fi
				CL=0
			fi
		fi
	fi

	PHP1=$(grep -m1 -e ^php1_release= "${CBOPTIONS}" | cut -f2 -d=)
	PHP2=$(grep -m1 -e ^php2_release= "${CBOPTIONS}" | cut -f2 -d=)
	PHP3=$(grep -m1 -e ^php3_release= "${CBOPTIONS}" | cut -f2 -d=)
	PHP4=$(grep -m1 -e ^php4_release= "${CBOPTIONS}" | cut -f2 -d=)
	PHP5=$(grep -m1 -e ^php5_release= "${CBOPTIONS}" | cut -f2 -d=)
	PHP6=$(grep -m1 -e ^php6_release= "${CBOPTIONS}" | cut -f2 -d=)
	PHP7=$(grep -m1 -e ^php7_release= "${CBOPTIONS}" | cut -f2 -d=)
	PHP8=$(grep -m1 -e ^php8_release= "${CBOPTIONS}" | cut -f2 -d=)
	PHP9=$(grep -m1 -e ^php9_release= "${CBOPTIONS}" | cut -f2 -d=)

	if [[ ${EXPORT} -eq 0 ]]; then
		printf "%-16s %-30s\t%s\n" "USER" "DOMAIN" "PHP"
		echo ---
	fi
	if [[ -n "$2" ]]; then
		USERSLIST="$2"
		if [[ $(grep -c -E ": ${USERSLIST}$" /etc/virtual/domainowners) -eq 0 ]]; then
			echo "User \"${USERSLIST}\" not found" >&2
			exit 1
		fi
	else
		USERSLIST=$(ls "${USERSDATA}" | sort -n)
	fi
	for USER in ${USERSLIST}; do
		for DOMAIN in `cat ${USERSDATA}/${USER}/domains.list`; do
			PHPVER=`grep -E "^php1_select=" ${USERSDATA}/${USER}/domains/${DOMAIN}.conf | cut -f2 -d=`
			if [[ ${PHPVER} -eq 9 ]]; then
				PHPSELECTED=${PHP9}
			elif [[ ${PHPVER} -eq 8 ]]; then
				PHPSELECTED=${PHP8}
			elif [[ ${PHPVER} -eq 7 ]]; then
				PHPSELECTED=${PHP7}
			elif [[ ${PHPVER} -eq 6 ]]; then
				PHPSELECTED=${PHP6}
			elif [[ ${PHPVER} -eq 5 ]]; then
				PHPSELECTED=${PHP5}
			elif [[ ${PHPVER} -eq 4 ]]; then
				PHPSELECTED=${PHP4}
			elif [[ ${PHPVER} -eq 3 ]]; then
				PHPSELECTED=${PHP3}
			elif [[ ${PHPVER} -eq 2 ]]; then
				PHPSELECTED=${PHP2}
			fi
			if [[ -z ${PHPVER} ]] || [[ ${PHPVER} -eq 1 ]] || [[ ${PHPSELECTED} == "no" ]]; then
				PHPSELECTED=${PHP1}
				if [[ ${CL} -eq 1 ]]; then
					CLVER=`/usr/bin/selectorctl -u ${USER} -c 2> /dev/null | cut -f1`
					if [[ "${CLVER}" == "native" ]]; then
						PHPSELECTED="${PHPSELECTED} (native)"
					elif [[ -z "${CLVER}" ]]; then
						PHPSELECTED="${PHPSELECTED} (not_in_cagefs)"
					else
						PHPSELECTED="${CLVER} (CL_selected)"
					fi
				fi
			fi
			if [[ ${EXPORT} -eq 1 ]]; then
				PHP=`echo -e ${PHPSELECTED} | awk '{print $1}'`
				printf "%s=%s\n" ${DOMAIN} ${PHP}
			else
				printf "%-16s %-30s\t%s %s\n" ${USER} ${DOMAIN} ${PHPSELECTED}
			fi
		done
	done
}

phpSet () {

	if [[ -z $1 ]] || [[ -z $2 ]]; then
		echo "Wrong ooptions"
		echo "Example: da_cli.sh php set DOMAIN.TLD 7.2"
		echo "		 da_cli.sh php set USERNAME 7.2"
		exit 1
	fi

	USERNAME=$(grep -E "^$1: " -m1 /etc/virtual/domainowners | cut -f2 -d: | xargs)
	if [[ -z ${USERNAME} ]]; then
		USERNAME=$(grep -E ": $1$" -m1 /etc/virtual/domainowners | cut -f2 -d: | xargs)
		if [[ -z ${USERNAME} ]]; then
			echo "User/domain not found"
			exit 1
		fi
		DOMAINLIST=$(grep -E ": ${USERNAME}$" /etc/virtual/domainowners | cut -f1 -d: | xargs)
	else
		DOMAINLIST=$1
	fi

	PHPSELECTED="$2"
	CBOPTIONS="/usr/local/directadmin/custombuild/options.conf"

	if [[ -z ${USERNAME} ]]; then
		echo "Domain was not found"
		exit 1
	fi

	PHPVER=$(grep -e "^php._release=${PHPSELECTED}$" "${CBOPTIONS}" | sed -e 's/php\(.\)_release=.*/\1/g')

	for DOMAIN in ${DOMAINLIST}; do
		if [[ -z ${PHPVER} ]]; then
			printf "\nDOMAIN: %s - PHP version \"%s\" does not exist. Available versions: " "${DOMAIN}" "${PHPSELECTED}"
			grep -e "^php._release=" ${CBOPTIONS} | grep -v _release=no |  xargs
			break
		fi
		PHPSELECT_JSON=$(cat <<- EOF
		{
			"php1_select": "${PHPVER}",
			"domain": "${DOMAIN}",
			"json": "yes",
			"action": "php_selector",
			"save": "yes"
		}
		EOF
		)
		printf "\nDOMAIN: %s " "${DOMAIN}"
		curl -k -X -u "$(/usr/local/directadmin/directadmin root-auth-url --user="${USERNAME}")/CMD_DOMAIN?json=yes" --request "POST" --data "${PHPSELECT_JSON}"
	done
}

phpExport() {
	USERNAME="$2"
	FILENAME="$1"
	EXPORT=1
	phpList "${EXPORT}" "${USERNAME}" > "${FILENAME}"
	echo "Export to \"${FILENAME}\" done"
}

phpImport() {
	FILENAME=$1
	if [[ -f ${FILENAME} ]]; then
		while read -r LINE
		do
			DOMAIN=$(echo "${LINE}" | cut -f1 -d=)
			PHPVER=$(echo "${LINE}" | cut -f2 -d=)
			phpSet "${DOMAIN}" "${PHPVER}"
		done < "${FILENAME}"
	else
		echo "Filename \"${FILENAME}\" does not exist"
		exit 1
	fi
}

ipCommands () {
	[[ -z $3 ]] && listFunctions
	case "$1:$2" in
		users:export) ipUsersExport "$3" ;;
		users:import) ipUsersImport "$3" ;;
		domains:export) echo "domains export" ;;
		domains:import) echo "domains import" ;;
		*) listFunctions; exit 1 ;;
	esac
}

ipUsersExport () {
	echo "Exporting IP addreses"
	[[ -z "$1" ]] && exit 1
	local data_dir=/usr/local/directadmin/data
	local tmp_dir
	tmp_dir=$(mktemp -d)
	cp -p    "${data_dir}/admin/ip.list" "${tmp_dir}"
	cp -p -r "${data_dir}/admin/ips"     "${tmp_dir}"

        for username in $(find "${data_dir}/users" -maxdepth 1 -mindepth 1 -type d -printf "%f\n"); do
		mkdir -p "${tmp_dir}/users/${username}/domains/" || exit
		if [[ -f "${data_dir}/users/${username}/reseller.conf" ]]; then
			cp -p                     "${data_dir}/users/${username}/ip.list"         "${tmp_dir}/users/${username}/"
			grep -E "^(ip|serverip)=" "${data_dir}/users/${username}/reseller.conf" > "${tmp_dir}/users/${username}/reseller.conf.part"
		fi

		cp -p          "${data_dir}/users/${username}/user_ip.list"  "${tmp_dir}/users/${username}/"
		grep -E '^ip=' "${data_dir}/users/${username}/user.conf"   > "${tmp_dir}/users/${username}/user.conf.part"


		for domain in $(find "${data_dir}/users/${username}/domains/" -maxdepth 1 -type f -name "*.ip_list" -printf "%f\n" | sed -e 's/\.ip_list//g' ); do
			cp -p          "${data_dir}/users/${username}/domains/${domain}.ip_list" "${tmp_dir}/users/${username}/domains/"
			grep -E '^ip=' "${data_dir}/users/${username}/domains/${domain}.conf"  > "${tmp_dir}/users/${username}/domains/${domain}.conf.part"
		done
	done
	tar -czf "$1.tar.gz" -C "${tmp_dir}" ip.list ips users || exit 1
	rm -rf "${tmp_dir}"
	echo "Exported to $1.tar.gz"
}

checkResellerIp() {
	reseller=$1
	ip=$2
	if ! grep -qE "^${ip}$" "${users_dir}/${reseller}/ip.list"; then
		echo "WARNING: ${username} owner was missing IP ${ip}, adding to his list"
		echo "${ip}" >> "${users_dir}/${reseller}/ip.list"
	fi
}

changeUserIp() {
	local users_dir=/usr/local/directadmin/data/users
	username=$1
	ip=$2
	reseller=$(grep ^creator= "${users_dir}/${username}/user.conf" | cut -f2 -d=)
	checkResellerIp "${reseller}" "${ip}"

	local json_data
	json_data=$(cat <<- EOF
	{
		"user": "${username}",
		"ip": "${ip}",
		"json": "yes",
		"action": "ip"
	}
	EOF
	)

	curl --silent -k -X -u "$(/usr/local/directadmin/directadmin api-url --user="${reseller}")/CMD_MODIFY_USER?json=yes" --request "POST" --data "${json_data}" -o /dev/null
}

addUserIp() {
	local users_dir=/usr/local/directadmin/data/users
	username=$1
	ip=$2
	reseller=$(grep ^creator= "${users_dir}/${username}/user.conf" | cut -f2 -d=)
	checkResellerIp "${reseller}" "${ip}"

	local json_data
	json_data=$(cat <<- EOF
	{
		"user": "${username}",
		"extra_ip": "${ip}",
		"json": "yes",
		"action": "multi_ip"
	}
	EOF
	)

	curl --silent -k -X -u "$(/usr/local/directadmin/directadmin api-url --user="${reseller}")/CMD_MODIFY_USER?json=yes" --request "POST" --data "${json_data}" -o /dev/null
}

changeDomainIp() {
	local domain, ip
	domain=$1
	ip=$2
	username=$(grep "^${domain}:" | cut -f2 -d' ')

	local json_data
	json_data=$(cat <<- EOF
	{
		"domain": "${domain}",
		"ip": "${ip}",
		"dns": "yes",
		"json": "yes",
		"action": "multi_ip",
		"add": "yes"
	}
	EOF
	)

	curl --silent -k -X -u "$(/usr/local/directadmin/directadmin api-url --user="${username}")/CMD_DOMAIN?json=yes" --request "POST" --data "${json_data}" -o /dev/null
}

deleteDomainIp() {
	local domain, ip
	domain=$1
	ip=$2
	username=$(grep "^${domain}:" | cut -f2 -d' ')

	local json_data
	json_data=$(cat <<- EOF
	{
		"domain": "${domain}",
		"removedns": "yes",
		"json": "yes",
		"action": "multi_ip",
		"delete": "yes",
		"select0": "${ip}"
	}
	EOF
	)

	curl --silent -k -X -u "$(/usr/local/directadmin/directadmin api-url --user="${username}")/CMD_DOMAIN?json=yes" --request "POST" --data "${json_data}" -o /dev/null
}


precheckUsers() {
	local tmp_dir=$1
	local users_dir=/usr/local/directadmin/data/users
	local OK=1

	echo -n "Precheck users and resellers..."
        for reseller_ip_list in $(find "${tmp_dir}/users" -maxdepth 2 -mindepth 2 -name 'ip.list' -printf '%P\n'); do
		if ! [[ -f "${data_dir}/users/${reseller_ip_list}" ]]; then
			echo "${reseller_ip_list} missing";
			OK=0
		fi
	done

	for username in $(find "${tmp_dir}/users" -maxdepth 1 -mindepth 1 -type d -printf "%f\n"); do
		if ! [[ -f "${users_dir}/${username}/user_ip.list" ]]; then
			echo "${username} user_ip.list missing"
			OK=0
		fi
		for domain_ips in $(find "${tmp_dir}/users/${username}/domains" -maxdepth 1 -mindepth 1 -type f -name "*.ip_list" -printf "%f\n"); do
			if ! [[ -f "${users_dir}/${username}/domains/${domain_ips}" ]]; then
				echo "${username} has missing ${domain_ips}"
				OK=0
			fi
		done
	done

	if [[ ${OK} -ne 1 ]]; then
		echo "Precheck failed. Have you really restored all the resellers, users and domains?"
		rm -rf "${tmp_dir}"
		exit 1
	fi
	echo "OK"
}

ipUsersImport() {
	echo "Importing IP addresses"
	[[ -z "$1" ]] && exit 1
	local data_dir=/usr/local/directadmin/data
	local tmp_dir
	tmp_dir=$(mktemp -d)
	bkp="users_bkp_$(date +%s)"
	echo -n "Making users backup to ${data_dir}/${bkp}..."
	cp -p -r "${data_dir}/users" "${data_dir}/${bkp}" || exit 1
	echo "OK"
	tar -C "${tmp_dir}" -zxf "$1.tar.gz" || exit

	precheckUsers "${tmp_dir}"

	current_server_ip=$(basename "$(grep "status=server" "${data_dir}"/admin/ips/* -l)")
	temp_server_ip=$(basename "$(grep "status=server" "${tmp_dir}"/ips/* -l)")
	if [[ -z "${temp_server_ip}" ]]; then
		echo "Could not detect the server IP from the import file!"
		rm -rf "${tmp_dir}"
		exit 1
	fi
	if [[ "${current_server_ip}" == "${temp_server_ip}" ]]; then
		echo "Server IP is already migrated! Something is wrong, bailing out..."
		rm -rf "${tmp_dir}"
		exit 1
	fi

	cp -p -f "${tmp_dir}/ip.list" "${data_dir}/admin/ip.list"
	cp -p -f "${tmp_dir}"/ips/*   "${data_dir}/admin/ips/"
	sed -i -e 's/status=owned/status=free/g' "${data_dir}"/admin/ips/* # owned IP cannot be assigned twice

	echo "Restore reseller ip lists and settings"
	for username in $(find "${tmp_dir}/users" -maxdepth 2 -mindepth 2 -name 'ip.list' -printf '%P\n' | cut -f1 -d/); do
		cp -p -f "${tmp_dir}/users/${username}/ip.list" "${data_dir}/users/${username}/ip.list"
		ip=$(grep -E ^ip= "${tmp_dir}/users/${username}/reseller.conf.part" | cut -f2 -d=)
		sed -i -e "s/^ip=.*/ip=${ip}/g" "${data_dir}/users/${username}/reseller.conf"
		serverip=$(grep -E ^serverip= "${tmp_dir}/users/${username}/reseller.conf.part" | cut -f2 -d=)
		sed -i -e "s/^serverip=.*/serverip=${serverip}/g" "${data_dir}/users/${username}/reseller.conf"
	done

	echo "User ip lists"
	for username in $(find "${tmp_dir}/users" -maxdepth 1 -mindepth 1 -type d -printf "%f\n"); do
		user_temp_ip=$(grep ^ip= "${data_dir}/users/${username}/user.conf" | cut -f2 -d=)
		user_orig_ip=$(grep ^ip= "${tmp_dir}/users/${username}/user.conf.part" | cut -f2 -d=)
		if [[ "${user_temp_ip}" != "${user_orig_ip}" ]]; then
			changeUserIp "${username}" "${user_orig_ip}"
		fi
		for additional_user_ip in $(grep -vE "^${user_orig_ip}$" "${tmp_dir}/users/${username}/user_ip.list"); do
			if ! grep -qE "^${additional_user_ip}$" "${data_dir}/users/${username}/user_ip.list"; then
				addUserIp "${username}" "${additional_user_ip}"
			fi
			for domain in $(find "${tmp_dir}/users/${username}/domains/" -maxdepth 1 -mindepth 1 -type f -name '*.ip_list' -printf "%f\n" | sed -e 's/\.ip_list//g') ; do
				if   grep -q "^${additiona_user_ip}$"  "${tmp_dir}/users/${username}/domains/${domain}.ip_list" &&
				   ! grep -q "^${additiona_user_ip}$" "${data_dir}/users/${username}/domains/${domain}.ip_list"; then
					addDomainIp "${domain}" "${additional_user_ip}"
					if ! grep -q "^${current_user_ip}$"  "${tmp_dir}/users/${username}/domains/${domain}.ip_list" &&
					     grep -q "^${current_user_ip}$" "${data_dir}/users/${username}/domains/${domain}.ip_list"; then
						deleteDomainIp "${domain}" "$current_user_ip}"
					fi
				fi
			done
		done
	done

	rm -rf "${tmp_dir}"
	echo "finishing touch with ip swap to finish up the leftovers"
	/usr/local/directadmin/scripts/ipswap.sh "${current_server_ip}" "${temp_server_ip}"
	/usr/local/directadmin/scripts/startips
	echo "Done"
}

renameSingleDomain() {
	local current_domain=$1
	local new_domain=$2
	local username
	current_domain="$1"
	new_domain="$2"
	username=$(grep "^${current_domain}:" /etc/virtual/domainowners | cut -f2 -d' ')
	if [[ -z "${username}" ]]; then
		echo "\"${current_domain}\" doesn't seem to belong to any user"
		exit 1
	fi

	local json_data
	json_data=$(cat <<- EOF
	{
		"old_domain": "${current_domain}",
		"new_domain": "${new_domain}",
		"json": "yes"
	}
	EOF
	)
	echo "${current_domain}->${new_domain}"
	curl --silent -k -X -u "$(/usr/local/directadmin/directadmin api-url --user="${username}")/CMD_CHANGE_DOMAIN?json=yes" --request "POST" --data "${json_data}"
}

renameDomains() {
	if [[ -z "$1" ]]; then
		echo "Missing parameters"
		exit 1
	fi

	if [[ -n "$2" ]]; then
		echo "Single domain rename"
		renameSingleDomain "$1" "$2"
	else
		if ! [[ -f "$1" ]]; then
			echo "$1 File not found"
			exit 1
		fi

		local current_domain, new_domain
		while IFS= read -r line; do
			current_domain=$(echo "${line}" | awk '{print $1}')
			new_domain=$(echo "${line}" | awk '{print $2}')
			renameSingleDomain "${current_domain}" "${new_domain}"
		done < "$1"
	fi
}

createemptybackup() {
	
	json_data=$(cat <<- EOF
	{
		"who": "all",
		"skip_suspended": "no",
		"when": "cron",
		"minute": "0",
		"hour": "5",
		"dayofmonth": "*",
		"month": "*",
		"dayofweek": "*",
		"where": "local",
		"ftp_ip": "",
		"ftp_username": "",
		"ftp_password": "",
		"ftp_path": "/",
		"ftp_port": "21",
		"ftp_secure": "no",
		"append_to_path": "nothing",
		"custom_append": "",
		"what": "select",
		"json": "yes",
		"action": "create",
		"form_version": "4",
		"local_path": "/home/admin/admin_backups/ustawienia",
		"encryption_password": "",
		"option0": "subdomain",
		"option1": "ftp",
		"option2": "ftpsettings",
		"option3": "database",
		"option4": "forwarder",
		"option5": "email",
		"option6": "emailsettings",
		"option7": "vacation",
		"option8": "autoresponder",
		"option9": "list"
	}
	EOF
	)

	curl --silent -k -X -u "$(/usr/local/directadmin/directadmin api-url)/CMD_ADMIN_BACKUP?json=yes" --request "POST" --data "${json_data}"	
}

listFunctions () {
	echo "+---------------------------------------+"
	echo "| TASKS:"
	echo "| $0 createuser USERNAME PASSWORD DOMAIN <PACKAGE> <EMAIL>"
	echo "| $0 deleteuser USERNAME"
	echo "| $0 createdb DBNAME DBUSERNAME DBPASSWORD"
	echo "| $0 deletedb DBNAME"
	echo "| $0 createforwarder FORWARDER DESTINATION"
	echo "| $0 deleteforwarder FORWARDER"
	echo "| $0 createdomain USERNAME DOMAIN"
	echo "| $0 createdomain USERNAME list=file"
	echo "| $0 deletedomain USERNAME DOMAIN"
	echo "| $0 deletedomain USERNAME list=file"
	echo "| $0 enablessh USERNAME"
	echo "| $0 disablessh USERNAME"
	echo "| $0 docroot USERNAME DOMAIN DOCROOT"
	echo "| $0 createmail DOMAIN MBOX PASSWORD <SIZE>"
	echo "| $0 createmail FILENAME"
	echo "| $0 deletemail DOMAIN MBOX"
	echo "| $0 enabledkim domain"
	echo "| $0 disabledkim domain"
	echo "| $0 changemailpass DOMAIN MBOX PASSWORD"
	echo "| $0 changeuserpass LOGIN PASSWORD"
	echo "| $0 disablenamed"
	echo "| $0 enablenamed"
	echo "| $0 sethostname HOSTNAME"
	echo "| $0 multiserver CLIENTHOSTNAME CLIENTNAME"
	echo "| $0 enablemultiserver"
	echo "| $0 disablemultiserver"
	echo "| $0 enablemultiserverpage"
	echo "| $0 disablemultiserverpage"
	echo "| $0 enablecreateadmin"
	echo "| $0 disablecreateadmin"
	echo "| $0 php list <USERNAME>"
	echo "| $0 php set DOMAIN PHP_VERSION"
	echo "| $0 php set USER PHP_VERSION"
	echo "| $0 php export FILENAME <USERNAME>"
	echo "| $0 php import FILENAME"
	echo "| $0 ip users export FILENAME"
	echo "| $0 ip users import FILENAME"
	echo "| $0 renamedomain olddomain newdomain"
	echo "| $0 renamedomain FILENAME"
	echo "| $0 createemptybackup"
	echo "+--------------------------------------+"
}

case "$1" in
	createuser) createUser "$2" "$3" "$4" "$5" "$6" ;;
	deleteuser) deleteUser "$2" ;;
	createdb) createDB "$2" "$3" "$4" ;;
	deletedb) deleteDB "$2" ;;
	createforwarder) createForwarder "$2" "$3" ;;
	deleteforwarder) deleteForwarder "$2" ;;
	createdomain) createDomain "$2" "$3" ;;
	deletedomain) deleteDomain "$2" "$3" ;;
	enablessh) enableSSH "$2" ;;
	disablessh) disableSSH "$2" ;;
	docroot) docroot "$2" "$3" "$4" ;;
	createmail) createmail "$2" "$3" "$4" "$5" ;;
	deletemail) deletemail "$2" "$3" ;;
	enabledkim) enabledkim "$2" ;;
	disabledkim) disabledkim "$2" ;;
	changemailpass) changemailpass "$2" "$3" "$4" ;;
	changeuserpass) changeuserpass "$2" "$3" ;;
	disablenamed) disablenamed ;;
	enablenamed) enablenamed ;;
	sethostname) sethostname "$2" ;;
	multiserver) multiserver "$2" "$3" ;;
	enablemultiserver) enablemultiserver ;;
	disablemultiserver) disablemultiserver ;;
	enablemultiserverpage) enablemultiserverpage ;;
	disablemultiserverpage) disablemultiserverpage ;;
	enablecreateadmin) enablecreateadmin ;;
	disablecreateadmin) disablecreateadmin ;;
	php) phpCommands "$2" "$3" "$4" "$5" ;;
	ip) ipCommands "$2" "$3" "$4" ;;
	renamedomain) renameDomains "$2" "$3" ;;
	createemptybackup) createemptybackup ;;
	*) listFunctions ;;
esac
