#!/bin/sh
#
# livecd-online-repo	Try to enable online APT repository
#
# chkconfig: 345 95 05
# description:	aimed at hasher/mkimage livecd users
# config: /etc/sysconfig/livecd-online-repo

# Do not load RH compatibility interface.
WITHOUT_RC_COMPAT=1

# Source function library.
. /etc/init.d/functions

LOCKFILE=/var/lock/subsys/livecd-online-repo
RETVAL=0

# defaults
INTERNET='no'
HOST='http://ftp.altlinux.org'
TMOUT=10

# autodetects
host_arch="$(rpm --eval '%_HOST_cpu' || arch | sed 's,i686,i586,')"
arepo=""
if [ "$host_arch" = "x86_64" ]; then arepo="x86_32"; fi

# possible overrides
SourceIfNotEmpty /etc/sysconfig/livecd-online-repo

# Regexps from alterator-pkg
prefix_re="[[:space:]]*rpm[[:space:]]\+\([^[:space:]]\+[[:space:]]\+\)\?"
updates_re="${prefix_re}http:\/\/\([^[:space:]]\+\)[[:space:]]*"
repo_source='/etc/apt/sources.list.d/alt.list'

repo_on()
{
	for arch in "$host_arch" noarch "$arepo"; do
		sed "s/^#\(${updates_re}${arch}\)/\1/" -i $repo_source
#		grep "^${updates_re}${arch}" $repo_source ||:
	done
}

repo_off()
{
	for arch in "$host_arch" noarch "$arepo"; do
		sed "s/^\(${updates_re}${arch}\)/#\1/" -i $repo_source
	done
}

check_conn()
{
	# Detect working Internet connection
	echo -n "Connecting to $HOST: "
	if curl --connect-timeout "$TMOUT" "$HOST" >/dev/null 2>&1; then
		echo_success; echo; return 0
	else
		echo_failure; echo; return 1
	fi
}

start()
{
	# Make online repositories available
	check_conn && if [ -f "$repo_source" ]; then
		echo -n "Enabling online repositories: "
		if repo_on; then
			echo_success
			RETVAL=0
		else
			echo_failure
			RETVAL=1
		fi
		echo
	else
		echo -n "Nonexistant $repo_source"
		echo_failure
		echo
		RETVAL=2
	fi
	return $RETVAL
}

stop()
{
	echo -n "Disabling online repositories: "
	if repo_off; then
		echo_success
		RETVAL=0
	else
		echo_failure
		RETVAL=1
	fi
	echo
	return $RETVAL
}

restart()
{
	stop
	start
}

# See how we were called.
case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	reload)
		restart
		;;
	restart)
		restart
		;;
	condstop)
		if [ -e "$LOCKFILE" ]; then
			stop
		fi
		;;
	condrestart)
		if [ -e "$LOCKFILE" ]; then
			restart
		fi
		;;
	condreload)
		if [ -e "$LOCKFILE" ]; then
			restart
		fi
		;;
	status)
		egrep -Rhv '^#|^[[:blank:]]*$' \
			/etc/apt/sources.list \
			/etc/apt/sources.list.d/*.list
		RETVAL=$?
		;;
	*)
		msg_usage "${0##*/} {start|stop|reload|restart|condstop|condrestart|condreload|status}"
		RETVAL=1
esac

exit $RETVAL
