#!/usr/bin/env bash
#
# Solaris 12 base image build script. 
#
set -e

# TODO add optional package publisher origin

rootfsDir="$1"
shift

# base install
(
	set -x

	pkg image-create --full --zone \
		--facet facet.locale.*=false \
		--facet facet.locale.POSIX=true \
		--facet facet.doc=false \
		--facet facet.doc.*=false \
		"$rootfsDir"

	pkg -R "$rootfsDir" set-property use-system-repo true

	pkg -R "$rootfsDir" set-property flush-content-cache-on-success true

	pkg -R "$rootfsDir" install core-os
)

# Lay in stock configuration, set up milestone
# XXX This all may become optional in a base image
(
	# faster to build repository database on tmpfs
	REPO_DB=/system/volatile/repository.$$
	export SVCCFG_REPOSITORY=${REPO_DB}
	export SVCCFG_DOOR_PATH=$rootfsDir/system/volatile/tmp_repo_door

	# Import base manifests. NOTE These are a combination of basic requirement
	# and gleaned from container milestone manifest. They may change.
	for m in $rootfsDir/lib/svc/manifest/system/environment.xml \
		$rootfsDir/lib/svc/manifest/system/svc/global.xml \
		$rootfsDir/lib/svc/manifest/system/svc/restarter.xml \
		$rootfsDir/lib/svc/manifest/network/dns/client.xml \
		$rootfsDir/lib/svc/manifest/system/name-service/switch.xml \
		$rootfsDir/lib/svc/manifest/system/name-service/cache.xml \
		$rootfsDir/lib/svc/manifest/milestone/container.xml ; do
		svccfg import $m
	done

	# Apply system layer profile, deleting unnecessary dependencies
	svccfg apply $rootfsDir/etc/svc/profile/generic_container.xml 

	# XXX Even if we keep a repo in the base image, this is definitely optional
	svccfg apply $rootfsDir/etc/svc/profile/sysconfig/container_sc.xml

	for s in svc:/system/svc/restarter \
		svc:/system/environment \
		svc:/network/dns/client \
		svc:/system/name-service/switch \
		svc:/system/name-service/cache \
		svc:/system/svc/global \
		svc:/milestone/container ;do
		svccfg -s $s refresh
	done

	# now copy the built up repository into the base rootfs
	mv $REPO_DB $rootfsDir/etc/svc/repository.db
)

# pkg(1) needs the zoneproxy-client running in the container.
# use a simple wrapper to run it as needed.
# XXX maybe we go back to running this in SMF?
mv "$rootfsDir/usr/bin/pkg" "$rootfsDir/usr/bin/wrapped_pkg"
cat > "$rootfsDir/usr/bin/pkg" <<-'EOF'
#!/bin/sh
#
# THIS FILE CREATED DURING DOCKER BASE IMAGE CREATION
# 
# The Solaris base image uses the sysrepo proxy mechanism. The
# IPS client pkg(1) requires the zoneproxy-client to reach the
# remote publisher origins through the host. This wrapper script
# enables and disables the proxy client as needed. This is a
# temporary solution.

/usr/lib/zones/zoneproxy-client -s localhost:1008
PKG_SYSREPO_URL=http://localhost:1008 /usr/bin/wrapped_pkg "$@"
pkill -9 zoneproxy-client
EOF
chmod +x "$rootfsDir/usr/bin/pkg"
