#!/bin/bash
haveSerial=false
shouldWipe=false
serial=""
used_serial=""
forbidden_serials="b06474cb"

function usage {
	echo -e "Usage: $(basename $0) [OPTIONS] [FILES]"
	echo -e "       Flash Android images"
	echo -e ""
	echo -e "Available options:"
	echo -e "       -s              Specify the serial number of the device to flash"
	echo -e "                       If not provided, only one device should be connected in fastboot mode or in adb mode"
	echo -e "       -w              Wipe cache and data partition after flashing"
	echo -e ""
	echo -e "FILES is a list of file in .img separated by space"
	echo -e "If no FILES provied all the .img in the current directory will be flashed"
	echo -e "e.g. $(basename $0) -s 132456789 out/target/device/boot.img out/target/device/system.img"
}

function check_forbidden_serial {
	if [[ $forbidden_serials =~ $1 ]]; then
		echo "Error: You should not flash this device !"
		echo "       Goodbye!"
		exit 1
	fi
}

function check_fastboot_serial {
	serials=$(fastboot devices | grep "fastboot" | awk '{print $1}')
	nb_device=$(fastboot devices | grep "fastboot" | wc -l)
	if $haveSerial; then
		if [[ ! $serials =~ $serial ]]; then
			echo "Cannot find provided serial $serial: Expecting the device to be rebooting in fastboot mode "
		fi
		used_serial=$serial
	else
		if [[ $nb_device != 1 ]]; then
			echo "Error: Too much or no device connected!"
			echo "       Provide a serial number with -s option or disconnect a device"
			exit 1
		fi
		used_serial=$serials
	fi
	check_forbidden_serial $used_serial
}

function reboot_and_wait_for_device {
	check_forbidden_serial $1
	adb -s $1 reboot bootloader;
	fastboot devices | grep $1 >/dev/null 2>&1
	while [ $? == 1 ]; do
		sleep 1;
		echo "Waiting for $1 in fastboot mode..."
		fastboot devices | grep $1 >/dev/null 2>&1
	done
}

function check_presence {
	if $haveSerial ; then
		fastboot devices | grep $serial >/dev/null 2>&1
		if [[ $? == 1 ]] ; then
			adb devices | grep $serial >/dev/null 2>&1
			if [[ $? == 0 ]] ; then
				reboot_and_wait_for_device $serial
			else
				echo "Error: Cannot found device $serial"
				exit 1;
			fi
		fi
	else
		nb_dev=$(fastboot devices | grep "fastboot" | wc -l)
		if [[ $nb_dev == 0 ]]; then
			nb_dev=$(adb devices | grep "\<device\>"| wc -l )
			if [[ $nb_dev == 0 ]]; then
				echo "Error: Cannot found any device in fastboot or adb mode"
				exit 1;
			elif [[ $nb_dev == 1 ]]; then
				dev=$(adb devices | grep "\<device\>" | awk '{print $1}')
				echo "Reboot device $dev in fastboot mode"
				serial=$dev
				haveSerial=true
				reboot_and_wait_for_device $serial
			else
				echo "Too much adb devices connected. Select one with -s or disconnect a device or reboot one in fastboot mode"
				exit 1
			fi
		fi
	fi
}

while getopts ":s:w" opt; do
	case $opt in
		s) echo "Using Serial $OPTARG"
		serial=$OPTARG
		haveSerial=true
		;;
		w)
		shouldWipe=true
		;;
		\?)
		echo "Invalid option: -$OPTARG" >&2
		usage
		exit 1
		;;
	esac
done
shift $(( OPTIND - 1 ))

if $haveSerial ; then
	check_forbidden_serial $serial
fi

if [ $# -eq 0 ];
then
	imgList=$(ls *.img 2>/dev/null)
else
	imgList=$@
fi
echo "Images to flash: $imgList"


if [ -z "$imgList" ];
then
	echo "No img to Flash"
	exit 1
else
	check_presence
	check_fastboot_serial
	echo "Flashing images"
	for img in $imgList; do
		imageName=$(basename $img)
		imageName=${imageName%.img}
		fastboot -s $used_serial -S 256M flash ${imageName} $img;
		if $shouldWipe; then
			fastboot -s $used_serial -w
		fi
	done && fastboot reboot
fi
