#!/bin/zsh


# Copyright (c) 2007 by pr3d4t0r (tek_fox AT internet.lu)
#
# 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 2 of the License, or
# (at your option) any later version.
#
# 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 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#
# amaebi script -- GPLv2
#
# Move the Applications directory on an iPhone device from the
# small root partition to the large data partition to avoid the
# "Low disk space" error message.
#
# Instructions:
#
# First, copy amaebi to the /var in your iPhone.  Fugu is ideal
# for this purpose.  Log on to your iPhone:
#
# ssh -l root your.iphone.ip.address
#
# Then execute these commands:
# 
# chmod +x /var/amaebi
# /var/amaebi
#
# That's it!
#
# To roll back the changes:
#
# /var/amaebi rollback
#
# Please contact pr3d4t0r if you have any questions:
#
# http://ciurana.eu/site.php?page=contact
#
# Bug reports and suggestions welcome!


# *** Symbolic constant ***

OK="0"

VERSION="1.1"

MACHINE_TARGET="iPhone1,1"
DEFAULT_APPS_DIR="/Applications"
TARGET_APPS_DIR="/var/root/Applications_ROOT"

if [[ "$AMAEBI_DEBUG" = "true" ]]
then
  # Debug code
  MACHINE_TARGET="i386"
  DEFAULT_APPS_DIR="./Applications"
  TARGET_APPS_DIR="./ApplicationsTarget"
fi


# **** Main ***


device="$(uname -m)"
if [[ "$device" != "$MACHINE_TARGET" ]]
then
  echo "Device:  expected = $MACHINE_TARGET; found = $device"
  echo "Process stopped."
  exit 1
fi
echo "Begin $DEFAULT_APPS_DIR processing"
echo "Device:  $device"


if [[ -L "$DEFAULT_APPS_DIR" ]]
then

  if [[ "$1" == "rollback" ]]
  then
    echo "Rolling back from $TARGET_APPS_DIR to $DEFAULT_APPS_DIR"
    rm -f "$DEFAULT_APPS_DIR"
    cp -Rf "$TARGET_APPS_DIR" "$DEFAULT_APPS_DIR"
    rm -Rf "$TARGET_APPS_DIR"
    
    exit 4
  fi
  
  echo "It appears that amaebi already processed $DEFAULT_APPS_DIR on this device."
  exit 0
fi


echo "Copying $DEFAULT_APPS_DIR to $TARGET_APPS_DIR"
cp -R "$DEFAULT_APPS_DIR" "$TARGET_APPS_DIR"


echo "Removing $DEFAULT_APPS_DIR..."
rm -Rf "$DEFAULT_APPS_DIR"


if [[ "$?" == "$OK" ]]
then
  echo "Linking $TARGET_APPS_DIR as $DEFAULT_APPS_DIR"
  ln -s "$TARGET_APPS_DIR" "$DEFAULT_APPS_DIR"
else
  echo "Removing $DEFAULT_APPS_DIR failed.  Restore any files in $TARGET_APPS_DIR back before exiting."
  exit 3
fi


if [[ -L "$DEFAULT_APPS_DIR" ]]
then
  echo "$device: $DEFAULT_APPS_DIR now points at $TARGET_APPS_DIR"
fi


echo "End $DEFAULT_APPS_DIR processing"
