#!/bin/sh

SYSCONFIG="/etc/sysconfig/docker"
DONEFILE="/var/lib/docker/.suse-image-migration-v1to2-complete"
CLI_OPTS="$@"

# Use $DOCKER_OPTS from Docker's sysconfig. Since we patch the migrator to ignore
# unknown flags, we don't have to worry about new flags in this file.
if [ -f "${SYSCONFIG}" ]
then
	. "${SYSCONFIG}"
fi

cat <<EOF
SUSE :: additional migration options loaded
   -->    sysconfig: ${DOCKER_OPTS}
   --> command line: ${CLI_OPTS}
EOF

# Wrapper for the migrator.
do_migration() {
	/usr/lib/docker-image-migrator/docker-image-migrator $DOCKER_OPTS $CLI_OPTS "$@"
}

# We can't check what the old version of Docker is, so we have to just run the
# migrator each time if we haven't previously tagged the server as having completed
# the migration.
if ! [ -f "$DONEFILE" ]
then
	# Run automated driver.
	echo "SUSE :: attempting automated migration"
	do_migration && DRIVERS+="[auto]"

	# If the automated migration failed, we will re-try with every other driver.
	if [ "$?" != 0 ]
	then
		# Run the migration tool on each driver.
		for driver in {aufs,overlay,btrfs,vfs,devicemapper}
		do
			echo "SUSE :: attempting migration of driver '${driver}'"
			(do_migration -s "${driver}") && DRIVERS+=" ${driver}"
		done
	fi
fi

# If the migration failed here, we won't touch the file.
if [ -z "$DRIVERS" ]
then
	cat >&2 <<EOF
SUSE :: layer migration failed on $(date) as PID $$.
   --> could not migrate with any driver!
   --> make sure you provided any necessary storage options as arguments to this
   ... script or in the \$DOCKER_OPTS variable in /etc/sysconfig/docker.
EOF
	exit 1
fi

# Log the migration as being complete.
# And output it to the screen.
tee "$DONEFILE" <<EOF
SUSE :: layer migration complete on $(date) as PID $$.
    --> migrated drivers: ${DRIVERS}
	-->      DOCKER_OPTS: ${DOCKER_OPTS}
	-->         CLI_OPTS: ${CLI_OPTS}

You can now proceed with installing docker 1.10.

Be warned that, once you install docker 1.10, you should not downgrade back to 1.9.
Otherwise you will hit a known issue which is that, any image you pull, will get
unnamed once you update again to 1.10.

EOF
