#!/bin/sh
#  Copyright, 2016 Scott Moser <smoser@ubuntu.com>
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  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 General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see
#    <http://www.gnu.org/licenses/>.

PREREQS=""
case $1 in
	prereqs) echo "${PREREQS}"; exit 0;;
esac

VERBOSITY="1"

debug() {
	local v=$1
	shift
	[ $v -lt $VERBOSITY ] && return 0
	echo "::" "$@"
}

mount_tar() {
	local target="$1" url=""
	shift;
	mount -t tmpfs ${ROOTFLAGS} root_url "$target" || return

	local zopt=""
	for url in "$@"; do
		case "$url" in
			*.tar.gz|*.tgz) zopt="z";;
			*.tar.xz|*.txz) zopt="J";;
		esac
		debug 1 "# [$zopt] $url"
		wget "$url" -O - | tar -C "$target" -xp${zopt}f -
	done
	[ -x "$target/sbin" ]
}

mount_squash() {
	local target="$1" url="$2"
	if [ $# -gt 2 ]; then
		log_warn "too many arguments to mount_squash: $*"
		return 1
	fi
	debug 1 "mount_squash downloading $url to $target.img"
	wget "$url" -O "$target.img"
	debug 1 "mount -t squashfs -o loop ${ROOTFLAGS}" \
		"'$target.img' '$target'"
	mount -t squashfs -o loop ${ROOTFLAGS} \
		"$target.img" "$target" || return
}

mount_url() {
	local target="$1" urls="$2" firsturl="" helper=""
	local oifs="$IFS"
	IFS=","; set -- $urls; IFS="$oifs"
	firsturl="$1"
	shift

	case "$firsturl" in
		tar:http*) helper=mount_tar; firsturl="${firsturl#*:}";;
		squash:http*) helper=mount_squash; firsturl="${firsturl#*:}";;
		*.tar.??|*.t?z) helper=mount_tar;;
		*.squash|*.squashfs) helper=mount_squash;;
	esac
	if [ -z "$helper" ]; then
		log_warn "no helper identified for '$firsturl'"
		return 1
	fi
	[ -d "$target" ] || mkdir -p "$target" || return
	"$helper" "$target" "$firsturl" "$@"
}

. /scripts/functions

case "$ROOT" in
	http://*|*:http://*) :;;
	*) exit 0
esac
configure_networking || exit

debug 1 "root=$ROOT"
mount_url "${rootmnt}.tmp" "$ROOT" || exit

{
	echo 'ROOTFSTYPE="root_url"'
	echo "ROOTFLAGS=\"-o move\""
	echo "ROOT=\"$rootmnt.tmp\""
} > /conf/param.conf

# vi: ts=4 noexpandtab
