#!/bin/bash
# Part of the xs-activation package
#
# Originally based on a similarly named script in the xs-rsync
# package by Martin Langhoff <martin@laptop.org>
#
# Adapted for xs-activation
# by Douglas Bagnall <douglas@paradise.net.nz>
#
# Copyright: One Laptop per Child

set -e

VERBOSE=no

# all files fit FAT 8.3 limits to avoid LFN mangling
FILES="lease.sig d-lease.sig d-oats.sig server.pub server.pri"

TMPDEST=`mktemp -d -p /library/xs-activation/tmp`
#make sure the tmp directory goes on error

# combined with set -e, error() is called if something fails.
error(){
    logger -puser.err -t "xs-activation[$$]" "Error at line $(caller)"
    if [ -n "$TMPDEST" -a -d "$TMPDEST" ]; then
	rm -rf --one-file-system "$TMPDEST"
    fi

}
trap error ERR

# Log a string via the syslog facility.
log()
{
    if test $1 != debug || expr "$VERBOSE" : "[yY]" > /dev/null; then
	logger -p user.$1 -t "xs-activation[$$]" -- "$2"
    fi
}

die()
{
    log err "$1"
    exit 1
}

STEP=0
STEPS=5

HAVE=`df -B1K /library/xs-activation | tail -n1 | \
      perl -pe 'm/(\d+)\s+\d+\%/; $_=($1-1);'`
NEED=0

SRCDIR="$UM_MOUNTPOINT"
XSNAME=`hostname -d | cut -f1 -d. `
if [ -d "$UM_MOUNTPOINT/xs-activation/$XSNAME" ]; then
    SRCDIR="$UM_MOUNTPOINT/xs-activation/$XSNAME";
elif [ -d "$UM_MOUNTPOINT/xs-activation" ]; then
    SRCDIR="$UM_MOUNTPOINT/xs-activation";
fi

: $((STEP++))

log notice "[$STEP/$STEPS] Checking whether it has a manifest";

if [ -r $SRCDIR/manifest.sha1 ];then
    log notice "[2/$STEPS] Seems to have a manifest";
else
    log err "[2/$STEPS] Missing manifest"
    exit 1;
fi

: $((STEP++))
log notice "[$STEP/$STEPS] Scanning $SRCDIR for files";
for FILE in $FILES; do
    if [ -r "$SRCDIR/$FILE" ]; then
	log notice "[1/$STEPS] Found $FILE";
	FSIZE=`du -s -B1K "$SRCDIR/$FILE" | awk {'print $1'}`
	NEED=$((NEED+FSIZE))
    fi
done

## Do we have enough space?
# The imported data gets saved twice, and less effiently the
# second time (one key per file), so pretend it is 4 times as big.
# Measuring in kB.
if [ $(($NEED * 4)) -gt $HAVE ];then
    log err 'Not enough free space in /library for these keys';
    exit 1;
fi

# Copy to a tmp dir first, so that if the checksum fails the file is
# not left in a place where it might accidentally get imported.
: $((STEP++))
log notice "[$STEP/$STEPS] Copying files to tmpdir";

for FILE in $FILES; do
    if [ -r "$SRCDIR/$FILE" ]; then
	log notice "$FILE"
	cp "$SRCDIR/$FILE" "$TMPDEST/"
    fi
done

: $((STEP++))
log notice "[$STEP/$STEPS] Checking manifest and signature";
xs-sum -c "$SRCDIR/manifest.sha1" -d $TMPDEST || die "checksum problems"

: $((STEP++))
log notice "[$STEP/$STEPS] Importing the files";
(/usr/bin/xs-activation-import $TMPDEST 2>&1 ) | logger -p user.err -t "xs-activation[$$]"

: $((STEP++))
log notice "[$STEP/$STEPS] Finished.";

rm -fr --one-file-system "$TMPDEST"
