#!/bin/sh
# -*- coding: utf-8 -*-
# vim: ts=4 sw=4 et ai si
#
# Copyright (c) 2012-2013 Intel, Inc.
# License: GPLv2
# Authors: Anas Nashif <anas.nashif@intel.com>
#          William Douglas <william.douglas@intel.com>
#          Patrick McCarty <patrick.mccarty@linux.intel.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2,
# as published by the Free Software Foundation.
#
# This program 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.

# This script will flash an output device with a downloaded raw image
# from download.tizen.org.
# Any missing configurations will be asked to the user.
# Being connected to the internet before launching this script is
# better. If you aren't connected, a wifi configuration script will be fired.

echo -e "2\t2\t2\t2" > /proc/sys/kernel/printk

chvt 2

export HOME="/root"

# The partition to resize after flashing the raw image
partition=1
# Used to retrieve output of the other scripts
output_data_file="/tmp/system-installer.$$"
# Mount point used to change the keymap layout of weston on the device
mountpoint="/tmp/output_device_mount_point"
# Configuration file of system-installer
conf_file="/usr/sbin/installer.conf"
# Used to signal a bmaptool failure during download/flash
bmaptool_failure=""

. /usr/sbin/dialog-helper

# Simply read the configuration in $conf_file, exit if not found
function read_config {

    if [ ! -e $conf_file ]; then
        dialog --msgbox "Installation failure, missing $conf_file" 10 40
	sigint_handler
    else
        . $conf_file
    fi
}

# Download the raw image, decompress it and write it on the device
# When the image is written, the partition size is modified
function install_os {
    bmaptool copy "$IMAGE_URL" "$OUTDEV" |&
    sed -u -e '/copied/!d;s/\r/\n/g;s/.* \([0-9]\{1,3\}\)% .*/\1/g' |
    dialog --gauge "Downloading the image and copying on $OUTDEV" 10 100 0
    if [[ ${PIPESTATUS[0]} != 0 ]]; then
        bmaptool_failure="yes"
    	sigint_handler
    fi

    local RESIZEFS=yes

    if [ "$RESIZEFS" = "yes" ]; then
        # resize first partition
        # WARNING: this only works if the system is installed on a single partition
        newsz=20 # GB
        sfdisk -d $OUTDEV | 
        awk '$1=="'${OUTDEV}${partition}'" { sub("size=[^,]+","size="'${newsz}'*1024*1024*2)}1' >/tmp/newpart.lst
        sfdisk $OUTDEV </tmp/newpart.lst || true
        echo "Partition ${OUTDEV}${partition} resized to $newsz GB"

        # force kernel to reread partitions
        echo "Probing new partition table"
        partprobe $OUTDEV

        # resize filesystem
        echo "Resizing filesystem"
        resize2fs -f -p ${OUTDEV}${partition}
    fi
}

# Let the user choose between available keyboard layouts, then execute loadkeys
function select_keyboard_layout {
	while :; do
		/usr/sbin/select-keyboard-layout-util "$output_data_file" && break
		[ $? -eq 1 ] && sigint_handler
	done
	KEYBOARD_LAYOUT=$(cat "$output_data_file")
	rm -f "$output_data_file" 2>/dev/null
	loadkeys "$KEYBOARD_LAYOUT"
}

# Test connection to "http://download.tizen.org/",
# if we can't connect, we configure the keyboard layout (if not yet set)
# then we launch the wifi configuration script
function test_connection {
	curl --connect-timeout 10 -s "http://download.tizen.org/" > /dev/null
	if [[ $? != 0 ]]; then
		while :; do
			/usr/sbin/wifi-config && break
			[ $? -eq 1 ] && sigint_handler
		done
	fi
}

# Sets the keyboard layout accordingly to $KEYBOARD_LAYOUT
# in weston.ini on the device
function modify_weston_conf {
	local file="${mountpoint}/etc/xdg/weston/weston.ini"
	[ -f "$file" ] && sed -i -e "s/^#\[keyboard\]$/\[keyboard\]/; s/^#keymap_layout=.*/keymap_layout=$KEYBOARD_LAYOUT/" "$file"
}

function sigint_handler {
	local txt=""
	if [ "$bmaptool_failure" = "yes" ]; then
		txt+="Bmaptool failed to flash your device."
	else
		txt+="The installation was interrupted."
	fi
	txt+=" Do you want to reboot ? press 'Yes' to reboot and 'No' to restart the installation."
	dialog --yesno "$txt" 15 40 && /usr/sbin/reboot -f
	rm -f "$output_data_file" 2>/dev/null
	rm -rf "$mountpoint" 2>/dev/null
	[ -d "${OUTDEV}${partition}" ] && umount -l "${OUTDEV}${partition}" 2>/dev/null
	exec /usr/sbin/system-installer
}

trap "sigint_handler" SIGINT

read_config

[ -z "$KEYBOARD_LAYOUT" ] && select_keyboard_layout

if [ -z "$IMAGE_URL" ]; then 
	test_connection
	while :; do
		/usr/sbin/url-utils "$output_data_file" && break
		[ $? -eq 1 ] && sigint_handler
	done
	IMAGE_URL=$(cat "$output_data_file")
elif ! curl --fail -I "$IMAGE_URL" > /dev/null ; then
	echo "The image url couldn't be reached, please verify that the url is correct."
	exit 1
fi

if [ -z "$OUTDEV" ]; then
	while :; do
		/usr/sbin/select-disk-util "$output_data_file" && break
		[ $? -eq 1 ] && sigint_handler
	done
	OUTDEV=$(cat "$output_data_file")
elif [ ! -b "$OUTDEV" ]; then
	dialog --msgbox "The output device is not a block device." 10 40
	sigint_handler
fi

rm -f "$output_data_file" 2>/dev/null

dialog --yesno "Do you whant to proceed with the installation ? All your data on the target device will be lost." 10 40 || sigint_handler

# Download and install the image
install_os

# Mounting device
mkdir -p "$mountpoint"
mount "${OUTDEV}${partition}" "$mountpoint"

modify_weston_conf

# Unmounting device
sync && sync
[ -d "${OUTDEV}${partition}" ] && umount -l "${OUTDEV}${partition}"

dialog --msgbox "The default password for all users is 'tizen'. Hit Enter to reboot and then remove the usb stick." 10 40 && /usr/sbin/reboot -f
