#!/bin/sh
# Copyright 2010 Palm, Inc.  All Rights Reserved.

# Save placeholder tarfiles for the files that will be moved into the file
# cache partition (saved-data.tar.gz) and var (saved-var.tar.gz).
# If tar files do not fit in /media/internal, return the size in MB of the
# tar files that do not fit so that user can make room for them.

SAVE_DIR=/media/internal/save_for_software_update
UPD_DIR=/var/lib/update
SAVE_DATA_FILE=saved-data.tar.gz
SAVE_VAR_FILE=saved-var.tar.gz
DATA_FILES="/var/luna/data/attachments /var/luna/data/emails /var/luna/files"
DATA_SIZE=0
VAR_SIZE=0
LOG=/var/log/updated.log


mkdir -p $SAVE_DIR

# First create the placeholder for the data tarfile.  Since the OS is
# running, tar will return an error if it encounters a files that is being
# modified.  This often happens with /var/luna/data/mediadb.db3-journal, an
# ephemeral file.  Ignore this with the -ignore-failed-read option, since
# /var will be properly saved when user processes are shut down for the
# update installation.
if ! tar --ignore-failed-read -cvzf $SAVE_DIR/$SAVE_DATA_FILE $DATA_FILES
then
    # remove empty tarfile
    rm -f $SAVE_DIR/$SAVE_DATA_FILE
    
    # create tmp tarfile in update partition so its size can be determined
    if ! tar --ignore-failed-read -cvzf $UPD_DIR/$SAVE_DATA_FILE $DATA_FILES \
        | tee -a $LOG 2>&1
    then
        echo "$0: Unable to save data" >> $LOG
        exit -1
    fi

    DATA_SIZE=`du -m $UPD_DIR/$SAVE_DATA_FILE | cut -f 1`
    DATA_SIZE=`expr $DATA_SIZE + 1`
    rm -f $UPD_DIR/$SAVE_DATA_FILE
fi

# then create the placeholder for the var tarfile
EXCL_ARGS="--exclude=/var/log --exclude=/var/tmp --exclude=/var/lib/update --exclude=/var/lib/software/tmp --exclude=/var/luna/data/attachments --exclude=/var/luna/data/emails --exclude=/var/luna/files --exclude=/var/palm/jail"

if ! tar --ignore-failed-read -cvzf $SAVE_DIR/$SAVE_VAR_FILE $EXCL_ARGS /var
then
    rm -f $SAVE_DIR/$SAVE_VAR_FILE
    
    if ! tar --ignore-failed-read -cvzf $UPD_DIR/$SAVE_VAR_FILE $EXCL_ARGS \
        /var | tee -a $LOG 2>&1
    then
        echo "Unable to save var" >> $LOG
        exit -1
    fi
    
    VAR_SIZE=`du -m $UPD_DIR/$SAVE_VAR_FILE | cut -f 1`
    VAR_SIZE=`expr $VAR_SIZE + 1`
    rm -f $UPD_DIR/$SAVE_VAR_FILE
fi

NEEDED_SPACE=`expr $DATA_SIZE + $VAR_SIZE`
if [ $NEEDED_SPACE -eq 0 ]
then
    touch $SAVE_DIR/backup-ok
else
    echo "$0: need $NEEDED_SPACE MB free space to save data and var"
fi

exit $NEEDED_SPACE
