#!/bin/bash
#  cloud - Cloud management support

set -e


######
# Settings

sys_cloud_config_init() {
	lib_setting_vars -ro cloud_confdir cloud_datadir

	lib_setting_vars --null cloud_domain
	lib_setting_arrays \
		cloud_net_dns cloud_net_addrs cloud_net_masks

	cloud_confdir="$confdir/cloud"
	cloud_datadir="$datadir/cloud"
}


######
# Clouds

cloud_filename() {
	local -a parts=( "$cloud_confdir" "$@" )
	local IFS="/"
	echo "${parts[*]}"
}

cloud_list() {
	[ -d "$cloud_confdir" ] || error "no clouds exist"
	(cd "$cloud_confdir" && find . -type d | sed -e 's,^\./,,' -e '/^\.$/d')
}

cloud_exists() {
	has_args 1 "$@"
	local cloud=$1

	local dir
	dir=$(cloud_filename "$cloud")
	test -d "$dir"
}

cloud_required() { cloud_exists "$1" || error "$1: cloud does not exist"; }

cloud_create() {
	has_args 1 "$@"
	local cloud=$1

	! cloud_exists "$cloud" || error "$cloud: cloud exists"

	local dir
	dir=$(cloud_filename "$cloud")
	run_mkdir "$dir"
	run touch "$dir/hosts"
}

cloud_delete() {
	has_args 1 "$@"
	local cloud=$1

	cloud_required "$cloud"

	local dir
	dir=$(cloud_filename "$cloud")
	run rm -rf "$dir"
}

for_each_cloud() { min_args 1 "$@"; for_each "$*" $(cloud_list); }

######
# Cloud networks
#   $cloud/networks file format:
#	$netname:$netaddr:$netmask

cloud_networks() {
	has_args 1 "$@";
	sed -e 's,:.*$,,' <"$(cloud_filename "$1" networks)"
}

######
# Cloud hosts
#   $cloud/hosts file format:
#	$hostname

cloud_hosts_filename() { echo "$(cloud_filename "$1" hosts)"; }

cloud_hosts() {
	has_args 1 "$@";
	grep -v -e '^#' -e '^$' "$(cloud_hosts_filename "$1")"
}

cloud_host_exists() {
	has_args 2 "$@"
	grep "^$2$" "$(cloud_hosts_filename "$1")" >/dev/null
}

cloud_host_enable() {
	has_args 1 "$@";
	run sed -i "s,^# *$2$,$2," "$(cloud_hosts_filename "$1")"
}

cloud_host_disable() {
	has_args 1 "$@";
	run sed -i "s,^$2$,# $2," "$(cloud_hosts_filename "$1")"
}

cloud_host_add() {
	min_args 2 "$@"
	local cloud=$1
	shift
	for_each _cloud_host_add "$@"
}
_cloud_host_add() {
	local name=$1
	if cloud_host_exists "$cloud" "$name"; then
		error "$cloud: host '$name' already part of cloud"
	fi
	echo "$name" >>"$(cloud_hosts_filename "$cloud")"
}

cloud_host_remove() {
	min_args 2 "$@"
	local cloud=$1
	shift
	for_each _cloud_host_remove "$@"
}
_cloud_host_remove() {
	local name=$1
	if ! cloud_host_exists "$cloud" "$name"; then
		error "$cloud: host '$name' not part of cloud"
	fi
	local hosts tmp
	hosts=$(cloud_hosts_filename "$cloud")
	tmp=$(cmd_tempfile)
	run grep -v "^$name$" "$hosts" >"$tmp"
	run mv "$tmp" "$hosts"
	rm -f "$tmp"
}

for_each_cloud_host() {
	min_args 2 "$@"
	local cloud=$1
	shift
	for_each "$*" $(cloud_hosts "$cloud")
}

View the Developer Guide Index

View the Reference Manual Index


Generated on Thu May 4 19:00:23 PDT 2017 by mcsh i7 v0.19.0.