#!/bin/sh
#
#    orchestra-import-isos - sync and import Ubuntu isos into cobbler
#
#    Copyright (C) 2011 Canonical
#
#    Authors:
#		Marc Cluet <marc.cluet@canonical.com>
#		Dustin Kirkland <kirkland@canonical.com>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, version 3 of the License.
#
#    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 Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Ensure root
if [ "$(id -u)" != "0" ]; then
	echo "ERROR: $0 must run as root" 2>&1
	exit 1
fi

# Definitions for supported releases and architectures
[ -r /etc/orchestra/import_isos ] && . /etc/orchestra/import_isos
[ -n "$RELEASES" ] || RELEASES=$(distro-info --supported)
[ -n "$ARCHES" ] || ARCHES="amd64 i386"
[ -n "$KSDIR" ] || KSDIR="/var/lib/orchestra/kickstarts"
[ -n "$PRIORITY" ] || PRIORITY="critical"
[ -n "$LOCALE" ] || LOCALE="en_US"
[ -n "$MGMTCLASS_AVAILABLE" ] || MGMTCLASS_AVAILABLE="orchestra-juju-available"
[ -n "$MGMTCLASS_ACQUIRED" ] || MGMTCLASS_ACQUIRED="orchestra-juju-acquired"
[ -n "$INTERFACE" ] || INTERFACE="auto"
[ -n "$KOPTS" ] || KOPTS="priority=$PRIORITY locale=$LOCALE netcfg/choose_interface=$INTERFACE"
if [ -n "$SERVER_IP" ]; then
	KOPTS="$KOPTS log_host=$SERVER_IP log_port=514"
else
	if grep -qs "^server: " /etc/cobbler/settings >/dev/null 2>&1; then
		SERVER_IP=$(grep "^server: " /etc/cobbler/settings | awk '{print $2}')
		KOPTS="$KOPTS log_host=$SERVER_IP log_port=514"
	fi
fi

# Wget and import net install ISOs
for r in $RELEASES; do
	for a in $ARCHES; do
		[ "$a" = "amd64" ] && a="x86_64"
		# Skip if cobbler already has this distro/arch combo
		if ! (cobbler distro list | grep -qs " $r-$a$"); then
			# Import the iso
			cobbler-ubuntu-import $r-$a
			cobbler profile edit --name="$r-$a" --kopts="$KOPTS"
		fi
		# Skip if cobbler already has this distro/arch profile
		if ! (cobbler profile list | grep -qs " $r-$a-juju$"); then
			# Add JuJu sub-profile based on the name of the imported ISO
			cobbler profile add --name="$r-$a-juju" --parent="$r-$a" --kickstart="$KSDIR/juju.preseed"
		fi
	done
done

# Add Management Classes for JuJu
for m in $MGMTCLASS_AVAILABLE $MGMTCLASS_ACQUIRED; do
	(cobbler mgmtclass list | grep -qs " $m$") || cobbler mgmtclass add --name="$m"
done

cobbler sync
