#!/bin/sh
# vim: et sw=2 st=2 ts=2 tw=0:
#
# GUI front end for persistence-wizard-cli
#
# 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; either version 3 of the License or (at
# your option) any later version.
# Please take a look at http://www.gnu.org/copyleft/gpl.htm
#
# Written by: Cyrille Pontvieux <jrd~at~enialis~dot~net>
# Modified by: Pierrick Le Brun <akuna~at~free~dot~fr>


# Gettext internationalization
export TEXTDOMAIN="persistence-wizard"
export TEXTDOMAINDIR="/usr/share/locale"
. gettext.sh

SCRIPT_NAME="$(basename $0)"
CLIPRGM=/usr/sbin/persistence-wizard-cli
RWMP=/tmp/persistentwiz-rwmountpoints
ROOT_DIR=
if [ -f /live/media/boot/liveboot ]; then
  SAVE_FILE_NAME="persistent"
fi
if [ -z "$ROOT_DIR" ]; then
  ROOT_DIR=
  SAVE_FILE_NAME="persistent"
fi

if [ ! $DISPLAY ]; then
  echo -e "`eval_gettext 'ERROR:'` `eval_gettext '$TEXTDOMAIN must be executed within a running X session.\n'`"
  exit 1
fi
if [ "$UID" != "0" ]; then
  echo "`eval_gettext 'ERROR:'` `eval_gettext 'You need to be root to run $SCRIPT_NAME'`"
  exit 1
fi
if [ ! `which zenity` ]; then
  echo "`eval_gettext 'ERROR:'` `eval_gettext 'zenity must be installed and in your PATH to run $SCRIPT_NAME'`"
  exit 1
fi
if [ ! `which mkfs.xfs` ]; then
  echo "`eval_gettext 'ERROR:'` `eval_gettext 'xfsprogs must be installed to run $SCRIPT_NAME'`"
  exit 1
fi

# find possible writable partitions and free size in megabytes
cat /dev/null > $RWMP
tempd=$(mktemp -d)
IFS="
"
for l in $(/sbin/blkid -o full); do
  if echo "$l" | grep -q '^/'; then
    device=$(echo "$l"|cut -d: -f1)
    LABEL=
    TYPE=
    eval $(echo "$l"|cut -d: -f2-)
    fs=$TYPE
    label="$LABEL "
    unset LABEL TYPE UUID SEC_TYPE
    mp=
    grep -q "^$device " /proc/mounts && mp=$(grep "^$device " /proc/mounts|awk '{print $2}')
    echo "$fs"|grep -q "vfat" && fs="vfat"
    echo "$fs"|grep -q "ntfs" && fs="ntfs"
    echo "$fs"|grep -q "ext[0-9]" && fs="ext"
    if [ "$fs" = "ext" -o "$fs" = "reiserfs" -o "$fs" = "xfs" -o "$fs" = "vfat" -o "$fs" = "ntfs" ]; then
      [ "$mp" = "(not" ] && mp=
      if [ -z "$mp" ]; then
        mp="$tempd/$(echo "$device"|sed 's:/:_:g')-$fs"
        mkdir -p "$mp"
        if [ "$fs" = "ntfs" ]; then
          mount.ntfs-3g "$device" "$mp"
        else
          mount "$device" "$mp"
        fi
        touch "$mp/_test_rw" 2> /dev/null
        if [ $? -ne 0 ]; then
          umount "$mp"
          rmdir "$mp"
          unset mp
        else
          rm "$mp/_test_rw"
        fi
      else
        touch "$mp/_test_rw" 2> /dev/null
        if [ $? -ne 0 ]; then
          unset mp
        else
          rm "$mp/_test_rw"
        fi
      fi
      if [ -n "$mp" ]; then
        disk=$(echo $device|tr -d '[0-9]'|sed 's:/.*/\([^/]\):\1:')
        [ -e /sys/block/$disk/removable ] && [ $(cat /sys/block/$disk/removable) -eq 1 ] && removable=`eval_gettext 'Yes'` || removable=`eval_gettext 'No'`
        size=$(df -BM -l "$mp"|tail -n1|awk '{print $4}'|tr -d M|rev|sed 's/.\{3\}/\0 /g'|rev)
        echo -e "$mp:$device:$label:$fs:$removable:$size" >> $RWMP
      fi
    fi
  fi
done
unset IFS # restore IFS

zenity --info \
 --title "`eval_gettext 'Persistence Wizard'`" \
 --window-icon /usr/share/icons/hicolor/128x128/apps/persistence-wizard.png \
 --text "`eval_gettext 'If you wish, you can save any of your work or modification performed while in a LiveCD session.\n\nTo do this however, you must first create a special "persistent file" which will have a pre-determined fixed-size and will be formatted as a linux file system.\n\nOnce this file is created, simply reboot the LiveCD for your changes to become persistent from then on.'`"

ACTUALSIZE=$(du -sh /live/media/|awk '{print $1}'|rev|sed 's/.\{3\}/\0 /g'|rev)
IFS=":
"
MOUNTPOINT=$(zenity \
  --title "`eval_gettext 'Mount point selection'`" \
  --window-icon /usr/share/icons/hicolor/128x128/apps/persistence-wizard.png \
  --list \
  --text "`eval_gettext 'The actual used memory size is $ACTUALSIZE.\nChoose the mountpoint where the persistent file must be created:'`" \
  --column "`eval_gettext 'Mount point'`" \
  --column "`eval_gettext 'Device'`" \
  --column "`eval_gettext 'Label'`" \
  --column "`eval_gettext 'Filesystem'`" \
  --column "`eval_gettext 'Removable'`" \
  --column "`eval_gettext 'Free size (in MB)'`" \
  --hide-column 1 \
  --width 500 --height 400 \
  $(tac $RWMP|sed 's/:/\n/g'))
unset IFS

if [ -z "$MOUNTPOINT" ]; then
  rm -f $RWMP
  find $tempd -type d -mindepth 1 -exec umount '{}' \;
  rm -rf $tempd
  exit 1
fi

MAXSIZE=$(grep "^$MOUNTPOINT:" $RWMP|cut -d: -f6|tr -d ' ')
# so there is still 250 MB remaining on the partition if possible
if [ $(($MAXSIZE - 250)) -gt 0 ]; then
  DEFSIZE=$(($MAXSIZE - 250))
else
  DEFSIZE=$MAXSIZE
fi
if [ $DEFSIZE -gt 500 ]; then # 500 MB max for default size
  DEFSIZE=500
fi

MAXSIZESEP=$(echo $MAXSIZE|rev|sed 's/.\{3\}/\0 /g'|rev)
SIZE=$(zenity \
  --title "`eval_gettext 'Size selection'`" \
  --window-icon /usr/share/icons/hicolor/128x128/apps/persistence-wizard.png \
  --entry \
  --text "`eval_gettext 'The actual used memory size is $ACTUALSIZE.\nSet the size in megabytes (maximum ${MAXSIZESEP}MB) for persistent file on $MOUNTPOINT:'`" \
  --entry-text $DEFSIZE)

if [ -z "$SIZE" ]; then
  rm -f $RWMP
  zenity \
    --title "`eval_gettext 'Error'`" \
    --window-icon /usr/share/icons/hicolor/128x128/apps/persistence-wizard.png \
    --error \
    --text "`eval_gettext 'No size was set.'` `eval_gettext 'The program will stop now!'`"  
  find $tempd -type d -mindepth 1 -exec umount '{}' \;
  rm -rf $tempd
  exit 1
elif [ $SIZE -gt $MAXSIZE ]; then
  rm -f $RWMP
  zenity \
    --title "`eval_gettext 'Error'`" \
    --window-icon /usr/share/icons/hicolor/128x128/apps/persistence-wizard.png \
    --error \
    --text "`eval_gettext 'The chosen size exceeds the available space ($SIZE > $MAXSIZE).'` `eval_gettext 'The program will stop now!'`"
  find $tempd -type d -mindepth 1 -exec umount '{}' \;
  rm -rf $tempd
  exit 1
fi

FORMAT=$(zenity \
--height=280 \
  --title "`eval_gettext 'File system selection'`" \
  --window-icon /usr/share/icons/hicolor/128x128/apps/persistence-wizard.png \
  --list \
  --text "`eval_gettext 'Select the file system that will be used to format your persistent file:'`" \
  --radiolist \
  --column "Select"  --column "File system" \
  FALSE xfs \
  FALSE ext2 \
  TRUE  ext3 \
  FALSE ext4 \
  FALSE reiserfs \
  FALSE vfat \
  FALSE ntfs)

if [ -z "$FORMAT" ]; then
  rm -f $RWMP
  zenity \
    --title "`eval_gettext 'Error'`" \
    --window-icon /usr/share/icons/hicolor/128x128/apps/persistence-wizard.png \
    --error \
    --text "`eval_gettext 'No file system was selected.'` `eval_gettext 'The program will stop now!'`"
  find $tempd -type d -mindepth 1 -exec umount '{}' \;
  rm -rf $tempd
  exit 1
fi

SAVEDIR="$MOUNTPOINT/$ROOT_DIR"
if [ ! -d "$SAVEDIR" ]; then
	mkdir -p "$SAVEDIR"
fi

cd $SAVEDIR
(yes | zenity --progress --pulsate --auto-close --auto-kill) &
$CLIPRGM $SAVE_FILE_NAME $SIZE $FORMAT
ret=$?
killall yes
sync
cd -

find $tempd -type d -mindepth 1 -maxdepth 1 -exec umount '{}' \;
rm -rf $tempd
DEVICE=$(grep "^$MOUNTPOINT:" $RWMP|cut -d: -f2)
rm -f $RWMP
if [ $ret -eq 0 ]; then
  zenity \
    --title "$TEXTDOMAIN" \
    --window-icon /usr/share/icons/hicolor/128x128/apps/persistence-wizard.png \
    --info \
    --text "`eval_gettext '$SAVE_FILE_NAME ($SIZE MB) correctly created in $SAVEDIR with $FORMAT file system.'`"
  if [ -d /live/media ]; then
    echo "$DEVICE:$ROOT_DIR/$SAVE_FILE_NAME" > /live/media/sync-persistence
  fi
  exit 0
else
  rm -f $RWMP
  zenity \
    --title "`eval_gettext 'Error'`" \
    --window-icon /usr/share/icons/hicolor/128x128/apps/persistence-wizard.png \
    --error \
    --text "`eval_gettext 'Something went wrong! $SAVE_FILE_NAME ($SIZE MB) cannot be created in $SAVEDIR.'`"
  exit 1
fi
