#!/system/bin/sh
TAG=checkgapps
ARC=/sdcard/gapps.zip

if [[ -e system/framework/com.google.android.maps.jar ]]; then
  echo "$TAG: Google apps are already installed"
else
  echo "$TAG: Looking for $ARC"

  MOUNTED_SD=0
  if ! mount | grep sdcard > /dev/null; then
    #Find the first fat partition. We do not go by partition
    #id as there are so many for different flavours of FAT(16/32) (/LBA)
    MMC=/dev/block/mmcblk0
    PARTITION=`busybox fdisk -l $MMC | awk '/^\// && /FAT/ {print $1;exit;}'`
    if [ -b "$PARTITION" ]; then
        echo "$TAG: mounting vfat partition $PARTITION"
        mount -t vfat -o dirsync,nosuid,nodev,noexec,uid=1000,gid=1015,fmask=0702,dmask=0702,shortname=mixed,utf8 $PARTITION /mnt/sdcard \
        || exit 1
        #&& chown system system /mnt/sdcard \
        #&& chmod 0077 /mnt/sdcard \
    else
        echo "$TAG: ERROR: Did not find a FAT partition on sdcard ($MMC). Partitions are:"
        #Print the known partitions
        busybox fdisk -l $MMC
        exit 1
    fi
    MOUNTED_SD=1
  fi

  mount -o remount,rw /system

  if [[ -e $ARC ]]; then
    echo -n "$TAG: Found $ARC, extracting ... "
    unzip -o $ARC -x 'META-INF*' -d / && echo "successful" || echo "failed"
  fi

  if [[ $MOUNTED_SD == 1 ]]; then
    umount /mnt/sdcard
  fi

  mount -o remount,ro /system
fi
