#!/bin/sh
# La Fonera archive extractor.
# Extract the signature and the .tar.gz archive from a .fon archive.
 
FON_FILE="$1"
 
if [ ! -f "$FON_FILE" -o -z "$FON_FILE" ]; then
    echo "Usage: $0 archive.fon"
    exit
fi
 
VERSION_FILE="$FON_FILE.version"
OFFSET_FILE="$FON_FILE.offset"
SIGNATURE_FILE="$FON_FILE.sig"
TAR_FILE="$FON_FILE.tgz"
 
dd if="$FON_FILE" of="$VERSION_FILE" bs=1 count=4 > /dev/null 2>&1
VERSION="$(cat $VERSION_FILE)"
if [ "$VERSION" = "FON3" ]; then
 echo "This is a FON reflash v2 archive"
elif [ "$VERSION" = "FON4" ]; then
 echo "This is a FON hotfix v2 archive"
else
 echo "ERROR: This is not a FON v2 archive"
 rm "$VERSION_FILE"
 exit 1
fi
rm "$VERSION_FILE"
 
dd if="$FON_FILE" of="$OFFSET_FILE" bs=1 count=3 skip=4 > /dev/null 2>&1
OFFSET="$(expr $(cat $OFFSET_FILE))"
if [ $OFFSET -eq 0 ]; then
 echo "ERROR: Offset too small"
 rm "$OFFSET_FILE"
 exit 1
fi
rm "$OFFSET_FILE"
 
dd if="$FON_FILE" of="$SIGNATURE_FILE" bs=1 count="$OFFSET" skip=7 > /dev/null 2>&1
TO_SKIP="$(expr $OFFSET + 7)"
dd if="$FON_FILE" of="$TAR_FILE" bs=1 skip="$TO_SKIP" > /dev/null 2>&1