#!/bin/sh

################################################################################
#      Copyright (C) 2009-2010 OpenELEC.tv
#      http://www.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/>.
################################################################################

# usage:   sudo ./create_installstick <drive>
# example: sudo ./create_installstick /dev/sdb

if [ "$(id -u)" != "0" ]; then
  clear
  echo "#########################################################"
  echo "# please execute with 'sudo' or -DANGEROUS!!!- as root  #"
  echo "# example: sudo ./create_installstick <drive>           #"
  echo "#########################################################"
  exit 1
fi

if [ -z "$1" ]; then
  clear
  echo "#########################################################"
  echo "# please execute with your drive as option              #"
  echo "# example: sudo ./create_installstick /dev/sdb          #"
  echo "#########################################################"
  exit 1
fi

DISK="$1"

### If DISK ends with a number, add "p1" instead of "1" for the first partition
case ${DISK#${DISK%?}} in
    ([0-9]) PART="${DISK}p1";;
    (*)     PART="${DISK}1";;
esac

clear
echo "#########################################################"
echo "#                                                       #"
echo "#              OpenELEC LIVE Installer                  #"
echo "#                                                       #"
echo "#########################################################"
echo "#                                                       #"
echo "#     This will wipe any data off your chosen drive     #"
echo "# Please read the instructions and use very carefully.. #"
echo "#                                                       #"
echo "#########################################################"

# check for some required tools

  # this is needed to create a bootloader
  which syslinux > /dev/null
  if [ "$?" = "1" ]; then
    clear
    echo "#########################################################"
    echo "#                                                       #"
    echo "# OpenELEC missing tool - Installation will quit        #"
    echo "#                                                       #"
    echo "#      We can't find the required tool \"syslinux\"     #"
    echo "#      on your system.                                  #"
    echo "#      Please install it via your package manager.      #"
    echo "#                                                       #"
    echo "#########################################################"
    exit 1
  fi

  # this is needed by syslinux
  which mcopy > /dev/null
    if [ "$?" = "1" ]; then
    clear
    echo "#########################################################"
    echo "#                                                       #"
    echo "# OpenELEC missing tool - Installation will quit        #"
    echo "#                                                       #"
    echo "#      We can't find the required tool \"mcopy\"        #"
    echo "#      on your system.                                  #"
    echo "#      Please install it via your package manager.      #"
    echo "#      NOTE: Some distributions call this package       #"
    echo "#      \"mtools\".                                      #"
    echo "#                                                       #"
    echo "#########################################################"
    exit 1
  fi

  # this is needed to partion the drive
  which parted > /dev/null
  if [ "$?" = "1" ]; then
    clear
    echo "#########################################################"
    echo "#                                                       #"
    echo "# OpenELEC missing tool - Installation will quit        #"
    echo "#                                                       #"
    echo "#      We can't find the required tool \"parted\"       #"
    echo "#      on your system.                                  #"
    echo "#      Please install it via your package manager.      #"
    echo "#                                                       #"
    echo "#########################################################"
    exit 1
  fi

  # this is needed to format the drive
  which mkfs.vfat > /dev/null
  if [ "$?" = "1" ]; then
    clear
    echo "#########################################################"
    echo "#                                                       #"
    echo "# OpenELEC.tv missing tool - Installation will quit     #"
    echo "#                                                       #"
    echo "#      We can't find the required tool \"mkfs.vfat\"    #"
    echo "#      on your system.                                  #"
    echo "#      Please install it via your package manager.      #"
    echo "#                                                       #"
    echo "#########################################################"
    exit 1
  fi

# check MD5 sums
  echo "checking MD5 sum..."

  md5sumFailed()
  {
    clear
    echo "#########################################################"
    echo "#                                                       #"
    echo "# OpenELEC failed md5 check - Installation will quit    #"
    echo "#                                                       #"
    echo "#      Your original download was probably corrupt.     #"
    echo "#   Please visit www.openelec.tv and get another copy   #"
    echo "#                                                       #"
    echo "#########################################################"
    exit 1
  }

  md5sum -c target/KERNEL.md5
  if [ "$?" = "1" ]; then
    md5sumFailed
  fi

  md5sum -c target/SYSTEM.md5
  if [ "$?" = "1" ]; then
    md5sumFailed
  fi

# nautilus/dolphin do late-mounting sometimes
# so race could happen (thanks Klojum)
  echo "please wait..."
  sleep 10

# quick and dirty: assume no more than 10 partitions. should be enough
  for i in `seq 1 10` ; do
    umount "${DISK}$i" 2>/dev/null
    umount "${DISK}p$i" 2>/dev/null
  done

# create a temp dir
  OE_TMP=$(mktemp -d)

# remove all partitions from the drive
  echo "writing new disklabel on $DISK (removing all partitions)..."
  dd if=/dev/zero of="$DISK" bs=4096 count=1024
  parted -s "$DISK" mklabel msdos

# create a single partition
  echo "creating a partition on $DISK..."
  parted -s "$DISK" unit cyl mkpart primary fat32 -- 0 -0

# make partition active (bootable)
  echo "marking partition active..."
  parted -s "$DISK" set 1 boot on

# tell kernel we have a new partition table
  echo "telling kernel we have a new partition table..."
  partprobe "$DISK"

# create filesystem
  echo "creating filesystem on $PART..."
  mkfs.vfat "$PART" -n OpenELEC

# install syslinux
  echo "installing syslinux to $PART..."
  syslinux -f "$PART"

# mount partition
  echo "mounting partition $PART on $OE_TMP..."
  mkdir -p $OE_TMP
  mount "$PART" $OE_TMP

# find UUID
  echo -n "finding partition UUID for $PART ..."
  UUID=`blkid $PART -s UUID -o value`
  echo "$UUID"

# create bootloader configuration
  echo "creating bootloader configuration..."

cat >$OE_TMP/syslinux.cfg << EOF
PROMPT 0
DEFAULT installer

LABEL installer
  KERNEL /KERNEL
  APPEND boot=UUID=$UUID installer quiet tty

EOF

# copy files
  echo "copying files to $PART..."
  cp target/KERNEL $OE_TMP
  cp target/KERNEL.md5 $OE_TMP
  cp target/SYSTEM $OE_TMP
  cp target/SYSTEM.md5 $OE_TMP
#  cp Autorun.inf $OE_TMP
  cp openelec.ico $OE_TMP
  cp CHANGELOG $OE_TMP
  cp INSTALL $OE_TMP
  cp README.md $OE_TMP
  cp RELEASE $OE_TMP

# sync disk
  echo "syncing disk..."
  sync

# unmount partition
  echo "unmounting partition $PART..."
  umount "$PART"

# write mbr
  echo "writing mbr..."
  if [ -f /usr/lib/syslinux/mbr.bin ]; then
    MBR="/usr/lib/syslinux/mbr.bin"       # example: debian, ubuntu
  elif [ -f /usr/share/syslinux/mbr.bin ]; then
    MBR="/usr/share/syslinux/mbr.bin"     # example: fedora
  elif [ -f /usr/lib/syslinux/bios/mbr.bin ]; then
    MBR="/usr/lib/syslinux/bios/mbr.bin"  # example: arch
  elif [ -f /usr/lib/syslinux/mbr/mbr.bin ]; then
    MBR="/usr/lib/syslinux/mbr/mbr.bin"   # example: Debian Jessie
   else
    echo "ERROR: Can't find syslinux's mbr.bin on Host OS" >&2
  fi

  if [ -n "$MBR" ]; then
    cat "$MBR" > "$DISK"
  fi

# syncing disk
  echo "syncing disk..."
  sync

# cleaning
  echo "cleaning tempdir..."
  rmdir $OE_TMP

echo "...installation finished"
