#!/bin/sh
set -e
. /usr/share/debconf/confmodule

save_logs () {
	save_to="$1"

	dir="$save_to/install" # dir name under 8 letters in case FS is fat
	c=1
	if [ -d "$dir" ]; then
		c=$(expr $c + 1)
		dir="$save_to/install.$c"
	fi
	mkdir "$dir"
	
	for file in \
	    /etc/lsb-release \
	    /var/log/messages \
	    /var/log/syslog \
	    /var/log/partman \
	    /var/lib/dpkg/status \
	    /var/log/hardware-summary \
	    /var/log/package-versions \
	    /var/log/*.ppm \
	    /usr/share/save-logs/install-report.template; do 
	    	if [ -e "$file" ]; then
			if ! cp "$file" "$dir"; then
				db_progress STOP
				exit 1
			fi
		fi
    	done
}

db_capb backup
	
IPADDR=$(ip addr | grep '^[[:space:]]*inet ' | grep -v "127\.0\." | \
	 head -n 1 | sed 's/.*inet \([0-9.]*\).*/\1/')

if [ -n "$IPADDR" ]; then
	db_set save-logs/menu web
fi
	 
db_input critical save-logs/menu || true
if ! db_go; then
	exit 10 # back to menu
fi
db_get save-logs/menu
METHOD="$RET"

# TODO: no state machine, so can't sanely backup after this point
db_capb

db_progress START 0 2 debian-installer/save-logs/title
report-hw > /var/log/hardware-summary
db_progress STEP 1

case "$METHOD" in
web)
	# The httpd serves files from /var/log, where almost
	# everything of interest is. Link a few other useful files to
	# there.
	ln -sf /etc/lsb-release /var/log
	ln -sf /var/lib/dpkg/status /var/log
	ln -sf /usr/share/save-logs/install-report.template /var/log

	# Kill existing server if one is already running
	: >/var/lib/httpd_stop # Blocks new listener processes from starting
	sleep 1
	for PID in $(pidof nc); do
		if grep -q "httpd" /proc/$PID/cmdline ; then
			# The server may already have gone if hit
			kill $PID 2>/dev/null || true
		fi
	done
	rm /var/lib/httpd_stop
	httpd

	db_progress STEP 1
	db_progress STOP
	if [ -z "$IPADDR" ]; then
		db_input critical save-logs/no_network || true
	else
		db_subst save-logs/httpd_running ADDRESS "$IPADDR"
		db_input critical save-logs/httpd_running || true
	fi
	db_go || true
;;
"mounted file system")
	if [ -e "/hd-media" ]; then
		db_set save-logs/directory "/hd-media"
	fi
	db_input critical save-logs/directory || true
	db_go || true
	db_get save-logs/directory
	if [ ! -d "$RET" ]; then
		db_subst save-logs/bad_directory DIR "$RET"
		db_input critical save-logs/bad_directory || true
		db_go || true
		db_progress STOP
	else
		save_logs "$RET"
		db_progress STEP 1
		db_progress STOP
	fi
;;
floppy)
	test -d /media || mkdir /media
	umount /media 2>/dev/null || true

	db_input critical save-logs/insert_floppy || [ $? -eq 30 ]
	db_go

	if mountmedia floppy ; then
		save_logs /media
		umount /media
		db_progress STEP 1
		db_progress STOP
	else
		db_progress STEP 1
		db_progress STOP
		db_input critical save-logs/floppy_mount_failed || [ $? -eq 30 ]
		db_go
	fi
;;
esac
