#!/bin/sh

# Find root NBD num, and corresponding root NBD num's SD lun num 
nbd=`sed '/ \/mnt\/root /!d;s/ .*/;;s/.*.nbd\(.\).*/\1/' < /proc/mounts`
if [ -z "$nbd" ]; then nbd=0; fi
eval `sdctl --stats`
x=`sed '/lun/!d;s/lun//;s/:.*//' < /proc/${nbdpid}/cmdline`
if [ "$x" -eq 1 ]; then
	if [ $nbd -eq 0 ]; then lun=1; else lun=0; fi 
else
	if [ $nbd -eq 0 ]; then lun=0; else lun=1; fi 
fi

# LUN#/NBD# overrides in file name
case $f in
*nbd0*)
	nbd=0
	;;
*nbd1*)
	nbd=1
	;;
*lun0*)
	lun=0
	;;
*lun1*)
	lun=1
	;;
esac

f=`basename $REQUEST_URI`
case $f in
root.dd|backup.dd|mbr.dd|root.tar.gz|kernel.dd|root.tar)
	d=`date -Iminutes | sed 's/+.*//;s/:/-/'`
	echo "Status: 302 Moved"
	echo -n "Location: "
	echo $REQUEST_URI | sed "s/\.dd$/-$d.dd/;s/\.tar/-$d.tar/"
	;;
backup*.img)
	echo "Content-Type: application/octet-stream"
	eval `sdctl --lun $lun 2>&1 | sed '/^cardsize_sectors=/!d'`
	let n="$cardsize_sectors / 128"
	let len="$n * 65536"
	echo "Content-Length: $len"
	echo
	sdctl --lun $lun -z 65536 -R $n 2>/dev/null
	;;
backup*.dd)
	echo "Content-Type: application/octet-stream"
	eval `sdctl --lun $lun --dblstor-disable 2>&1 | sed '/^cardsize_sectors=/!d'`
	let n="$cardsize_sectors / 128"
	let len="$n * 65536"
	echo "Content-Length: $len"
	echo
	sdctl --lun $lun -z 65536 -R $n --dblstor-disable 2>/dev/null
	;;
kernel*.dd)
	echo "Content-Type: application/octet-stream"
	kernel=`fdisk -l /dev/nbd${nbd} | sed '/da U/!d;s/ .*//;q'`
	echo -n "Content-Length: "
	blockdev --getsize64 $kernel
	echo
	cat $kernel
	;;
root*.dd)
	echo "Content-Type: application/octet-stream"
	r=`sed '/ \/mnt\/root /!d;s/ .*//' < /proc/mounts`
	if [ -z "$r" ]; then r="/dev/nbd${nbd}p2"; fi
	if [ ! -e "$r" ]; then r="/dev/null"; fi
	if [ -f /r ]; then read r < /r; fi
	sdpart=`echo $r | sed "/^\/dev\/nbd${nbd}p[0-9]/!d;s/\/dev\/nbd${nbd}p/part/"`
	if [ -n "$sdpart" ]; then
		eval `sdctl -P 2>&1 | sed "/^$sdpart/!d;s/[^_]*_//"`
		let sz="$sz / 128"
		let len="$sz * 65536"
		echo "Content-Length: $len"
		echo
		sdctl --lun $lun -z 65536 -R $sz -k $offs 2>/dev/null
	else
		if [ -b "$r" ]; then 
			echo -n "Content-Length: "
			blockdev --getsize64 $r
		fi
		echo
		cat $r
	fi
	;;
root*.tar.gz)
	echo "Content-Type: application/octet-stream"
	echo
	ver=`echo $f | sed 's/root-*\(.*\).tar.gz/\1/'` 
	echo $ver > /mnt/root.version
	tar -c -z -C /mnt/root -f - . ../root.version
	;;
root*.tar)
	echo "Content-Type: application/octet-stream"
	echo
	ver=`echo $f | sed 's/root-*\(.*\).tar/\1/'` 
	echo $ver > /mnt/root.version
	tar -c -C /mnt/root -f - . ../root.version
	;;
mbr*.dd)
	echo "Content-Type: application/octet-stream"
	echo "Content-Length: 512"
	echo
	dd if=/dev/nbd${nbd} bs=512 count=1
	;;
esac

