#!/bin/bash
if [ ! -e /var/run/remove_partitions ]; then
	echo "not exists /var/run/remove_partitions."
	exit 1
fi
#
# Check root permission
#
token_name="/var/run/remove_partitions_root_$RANDOM"
touch $token_name 2> /dev/null || true
if [ ! -e "$token_name" ]; then
	echo "not exists /var/run/remove_partitions."
	exit 1
fi
rm $token_name

#
# Device is not null
#
if [ "$1" = "" ];then
	echo "device is null"
	exit 1
fi

#
# Device exist
#
device="/dev/$1"
if [ ! -e "$device" ]; then
	echo "device not exists"
	exit 1
fi

#
# Device is removable
#
if [ "$2" != "--ignore-removable"  ];then 
	removable=$(cat /sys/block/$1/removable)
	if [ "$removable" = "0" ]; then
		echo "device isn't removable"
		##
		## Dialog para preguntar si se esta seguro
		echo "Device $1 isn't removable. Write yes to continue"
		read pass
		if [ "$pass" != "yes" ]; then
			exit 1
		fi
	fi
fi

umount ${device}? || true
# Delete partitions table
dd if=/dev/zero of=$device bs=512 count=1
# Create new partitions table
parted -s $device mklabel msdos 
# Create vfat 35 Mb partition with boot flag
parted -s $device unit MB mkpart primary fat32 0 150
parted -s $device set 1 boot on
# Format partition
partition=`get_first_partition $device`
if [ "$partition" = "" ];then
	echo "error"
	exit 1
fi
mkfs.vfat -F 32 ${partition}
# Mount partition
path_sd="/media/llxberry_$RANDOM"
mkdir -p $path_sd
mount ${partition} $path_sd
data_path=$(llx-berry-manager)

# Cp berryboot files
cp "$data_path"/* $path_sd

# TODO 
# Modify cmdline.txt and replace _@_server_@_ by SRV_IP n4d var
#
#eval `n4d-vars getvalues SRV_IP`
#sed -i -e "s%_@_SRV_IP_@_%${SRV_IP}%g" ${path_sd}/cmdline.txt

sync

umount $path_sd 
rm -rf $path_sd

rm /var/run/remove_partitions
# This line is very important to n4d clients
echo "Ok"