#!/bin/bash

# Copyright (C) 2014-2015 Red Hat Inc.
# SPDX-License-Identifier:  GPL-2.0+

# usage message
usage() {
    echo "
Usage: $(basename ${0}) <options>

   --media=DEVICE   - media device file (/dev/[sdX|mmcblkX])
   --url=URL	    - Optional URL, Mastermirror used as default

Example: $(basename ${0}) --media=/dev/mmcblk0"
}

# check the args
while [ $# -gt 0 ]; do
    case $1 in
        --debug)
            set -x
            ;;
        -h|--help)
            usage
            ;;
	--media*)
            if echo $1 | grep '=' >/dev/null ; then
                MEDIA=$(echo $1 | sed 's/^--media=//')
            else
                MEDIA=$2
                shift
            fi
            ;;
	--url*)
	    if echo $1 | grep '=' >/dev/null ; then
		URL=$(echo $1 | sed 's/^--url=//')
	    else
		URL=$2
		shift
	    fi
            ;;
        *)
            echo "$(basename ${0}): Error - ${1}"
            usage
            exit 1
            ;;
        esac
    shift
done

# check if media exists
if [[ ! -e $MEDIA ]] ; then 
	echo "Missing media"
	usage
	exit 1
fi 
# check if url specified if not use mastermirror
if [[ $URL = '' ]] ; then
	URL="http://dl.fedoraproject.org/pub/alt/stage/22_Alpha_RC3/Server/armhfp/os/"
fi

# unmount media
echo "= Umounting $MEDIA."
sudo umount $MEDIA* &> /dev/null

# create partition 
echo "= Creating partition."
sudo parted -s $MEDIA mklabel msdos &> /dev/null
sudo parted -s -a optimal $MEDIA mkpart primary ext4 1 512 &> /dev/null

# re-read table
sudo partprobe $MEDIA

# check media type /dev/sdX or /dev/mmcblkX
case $MEDIA in
        "/dev/mmcblk"*)
                        PART1="${MEDIA}p1"
                        ;;
        *)
                        PART1="${MEDIA}1"
                        ;;
esac

# create filesystem
echo "= Creating filesystem."
sudo mkfs.ext4 $PART1 &> /dev/null

# create temp dir
echo "= Making temporary directory."
sudo rm -rf /tmp/install-card
mkdir /tmp/install-card
sudo mount $PART1 /tmp/install-card

# get pxe images and dtb files
sudo /usr/bin/rsync -ahH rsync://dl.fedoraproject.org/fedora-alt/stage/22_Alpha_RC3/Server/armhfp/os/images/pxeboot/ /tmp/install-card/

# make and populate the extlinux.conf
sudo mkdir /tmp/install-card/extlinux/
cat > /tmp/extlinux.conf << EOF
# extlinux.conf generated by script
ui menu.c32
menu autoboot Welcome to Fedora 22_Alpha Installer for ARM. Automatic boot in # second{,s}. Press a key for options.
menu title Fedora 22_Alpha Installer for ARM Boot Options.
menu hidden
timeout 20
totaltimeout 600

label Fedora 22_Alpha Installer for ARM
	kernel /vmlinuz
	append inst.repo=$URL
	fdtdir /dtb/
	initrd /initrd.img
EOF
sudo mv /tmp/extlinux.conf /tmp/install-card/extlinux/
sync
sudo umount $MEDIA* &> /dev/null
echo "= Complete!"
