#!/bin/bash
################################################################################
#  This file is part of OpenELEC - http://www.openelec.tv
#      Copyright (C) 2009-2013 Stephan Raue (stephan@openelec.tv)
#      Copyright (C) 2011-2013 Christian Hewitt (chewitt@openelec.tv)
#
#  OpenELEC 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.
#
#  OpenELEC 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 OpenELEC.  If not, see <http://www.gnu.org/licenses/>.
################################################################################

VERBOSE="FALSE" # set to TRUE to put this script in debug mode

banner(){
  clear
  echo ""
  echo "********************************************************************************"
  echo "*                                                                              *"
  echo "*                Welcome to the Lakka Mac OS X Livestick Creator!              *"
  echo "*                                                                              *"
  echo "********************************************************************************"
}

check_root(){
  if [ $UID != 0 ];then
    echo ""
    echo "FAIL: This script *must* be run as root!"
    echo ""
    exit 1
  fi
}

check_runlocation(){
  SCRIPT=$(pwd)
}

check_localtargetfolder(){
  if [ ! -f target/SYSTEM -a ! -f target/KERNEL ]; then
    echo ""
    echo "FAIL: Could not detect SYSTEM and KERNEL files. This script *must* be run from"
    echo "      the root folder of the Lakka image you downloaded!" 
    echo ""
    exit 1
  fi
}

check_distro(){
  DISTRO=$(uname -s)
  if [ $DISTRO != "Darwin" ]; then
    echo ""
    echo "FAIL: This script is only for Mac OS X systems, aborting!"
    echo ""
    exit 1
  fi
}

read_input(){
  local MESSAGE="${1}"
  if [ -n "${MESSAGE}" ];then
    echo -n "${MESSAGE}"
  fi
  read INPUT
}

check_target(){
  echo ""
  echo "INFO: The following drives are available to create the Lakka USB on:"
  echo ""
  diskutil list | grep 0: | grep -v disk0 | awk '{print "/dev/"$5 " "$3 $4}'
  echo ""
  while [ -z ${INPUT} ];do
    read_input "INFO: Please enter the target device (e.g. /dev/disk1): "
    echo ""
  done
  TARGET=${INPUT}
}

warning(){
  local OUTPUT
  OUTPUT=$(fdisk ${TARGET} 2>/dev/null)
  if [ -z "${OUTPUT}" ];then
    echo "FAIL: Installation aborted! Device ${TARGET} is invalid"
    echo ""
    exit 1
  else
    diskutil list ${TARGET}
    echo ""
  fi
  CONTINUE=""
  echo -n "WARN: Continuing will erase all data from $TARGET, continue? (Y/n): "
  read CONTINUE
  if [ "${CONTINUE}" = "N" -o "${CONTINUE}" = "n" -o "${CONTINUE}" = "" ]; then
    echo ""	
    echo "FAIL: Installation aborted!"
    echo ""
    exit 1
  elif [ "${CONTINUE}" = "Y" -o "${CONTINUE}" = "y" ]; then 
    echo ""
  fi
}	

logoutput(){
  if [ "${VERBOSE}" = "TRUE" ]; then
    exec 3>&1
    exec 4>&2
  else
    exec 3> /dev/null
    exec 4> /dev/null
  fi
}

unmount_target(){
  for i in $(jot 10 1 10); do
    MOUNTED=$(mount | grep ${TARGET})
    if [ -z "${MOUNTED}" ]; then
      break
    else
      diskutil unmountDisk ${TARGET} 1>&3 2>&4
      sleep 1
    fi
  done
}

mount_target(){
  for i in $(jot 10 1 10); do
    MOUNTED=$(mount | grep ${TARGET})
    if [ -z "${MOUNTED}" ]; then
      diskutil mountDisk ${TARGET} 1>&3 2>&4
      sleep 1
    else
      break
    fi
  done
}

prepare_target(){
  echo "INFO: Erasing existing partition schemes on ${TARGET}"
  dd if=/dev/zero of=${TARGET} bs=512 count=100 1>&3 2>&4
  gpt destroy ${TARGET} 1>&3 2>&4
  echo "INFO: Creating MBR 'LAKKA' disk on ${TARGET}"
  diskutil eraseDisk MS-DOS LAKKA MBR ${TARGET} 1>&3 2>&4
  unmount_target
  chmod 755 3rdparty/macfiles/*
  cat 3rdparty/macfiles/mbr.bin > ${TARGET}
  mount_target
  3rdparty/macfiles/syslinux-mac -f --install ${TARGET}s1 1>&3 2>&4
}

create_partitions(){
  unmount_target
  echo "INFO: Creating partitions"
  fdisk -e ${TARGET} < 3rdparty/macfiles/fdisk.input 1>&3 2>&4
}

check_checksums(){
  MD5_KERNEL=$(md5 target/KERNEL | awk '{print $4}')
  MD5_SYSTEM=$(md5 target/SYSTEM | awk '{print $4}')
  KERNEL_DOT_MD5=$(cat target/KERNEL.md5 | awk '{print $1}')
  SYSTEM_DOT_MD5=$(cat target/SYSTEM.md5 | awk '{print $1}')
  if [ "${MD5_KERNEL}" = "${KERNEL_DOT_MD5}" -a "${MD5_SYSTEM}" = "${SYSTEM_DOT_MD5}" ]; then
    echo "INFO: MD5 checksums for SYSTEM and KERNEL match"
  else
    echo "FAIL: MD5 checksums for SYSTEM and KERNEL do not match!"
    exit 1
  fi
}

copy_files(){
  mount_target
  echo "INFO: Copying SYSTEM and KERNEL files to 'LAKKA'"
  cp -a target/KERNEL /Volumes/LAKKA/
  cp -a target/SYSTEM /Volumes/LAKKA/
  echo "INFO: Creating syslinux.cfg on 'LAKKA'"
  cat >/Volumes/LAKKA/syslinux.cfg << EOF
PROMPT 0
DEFAULT installer

LABEL installer
  MENU LABEL Run Lakka Installer
  KERNEL /KERNEL
  APPEND boot=LABEL=LAKKA installer quiet vga=current

EOF
}

check_filesystem(){
  unmount_target
  echo "INFO: Checking filesystem on ${TARGET}"
  fsck_msdos -y ${TARGET}s1 1>&3 2>&4
  unmount_target
}

end(){
  echo ""	
  echo "INFO: Livestick USB creation is complete!"
  echo ""
}

main(){
  check_root
  check_runlocation
  check_localtargetfolder
  check_distro
  check_target
  warning
  logoutput
  unmount_target
  prepare_target
  create_partitions
  check_checksums
  copy_files	
  check_filesystem
}

banner
main
end
exit 0
