#!/bin/bash
#  version date: 2010-06-13 22:36:00 -0400  
#  
#  '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 live-rw | \
        awk '{print \$4}' " root)
fi

echo -e "\n   Your Sugar Cellar storage space:\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 "   $freePortion % of the $denominator MiBytes allocated in LiveOS
    \r   persistent storage is free on this device.\n"
fi

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

df -Th
echo 

exit 0
