#!/bin/bash
#
#  'SugarCellar' reports on the availability of storage on a live 'Sugar on a
#   Stick' image. 
#
#  Copyright 2010, Sugar Labs
#  Frederick Grose <fgrose@sugarlabs.org>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; version 2 of the License.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU Library General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

export PATH=/sbin:/usr/sbin:$PATH
export \
   PS4='+(${LINENO}:${BASH_SOURCE}:${EUID}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'

SOURCEMNT=/mnt/live
LIVEOS=LiveOS

if [[ -b /dev/live ]]; then
    freePortion=$(su --session-command="dmsetup status | grep live-rw | \
        awk '{print \$5}' " root)
fi

echo -e "\n   The following storage space is in your Sugar Cellar:\n"

if [[ -n "$freePortion" ]]; then
    numerator=$(dc <<< "8k ${freePortion/\/*/} 2048 /p")    
    denominator=$(dc <<< "8k ${freePortion/*\//} 2048 /p")
    freePortion=$(dc <<< "8k 10 0.05 100 1 ${numerator} ${denominator} /-*+*p")
    freePortion=$(dc <<< "1k $freePortion 10 /p")
    denominator=$(dc <<< "8k 10 0.5 ${denominator} +*p")
    denominator=$(dc <<< "0k $denominator 10 /p")
    echo -e "   There is $freePortion % of the $denominator MiBytes in LiveOS
    \r   persistent storage that is free on this device.\n"
fi

if [[ -f $SOURCEMNT/$LIVEOS/home.img ]]; then
    denominator=$(du -s -b $SOURCEMNT/$LIVEOS/home.img | awk '{print $1;}')
    usedHome=$(du -s -b ${HOME}/ | awk '{print $1;}')
    freePortion=$(dc <<< "8k 10 0.05 100 1 $usedHome $denominator /-*+*p" )
    freePortion=$(dc <<< "1k $freePortion 10 /p")
    capacity=$(dc <<< "2k 10 0.5 $denominator 1024 1024 */+*p")
    capacity=$(dc <<< "0k $capacity 10 /p")
    echo -e "
    \r   There is $freePortion % of the $capacity MiBytes in the persistent
    \r   home directory that is free on this device.\n"
fi

df -h
echo 

exit 0
    
