#!/bin/sh

set -e

. /lib/partman/definitions.sh

mkdir -p /var/lib/partman/devices

echo "Starting the parted server"

if [ ! -f /var/run/parted_server.pid ]; then
    [ -d /var/run ] || mkdir /var/run
    parted_server
    RET=$?
    if [ $RET != 0 ]; then
        # TODO: How do we signal we couldn't start partman_server properly?
        exit $RET
    fi

    if [ -d /var/lib/partman/old_devices ]; then
	rm -rf /var/lib/partman/old_devices
    fi
    if [ -d $DEVICES ]; then
	mv $DEVICES /var/lib/partman/old_devices
    fi
    mkdir $DEVICES || true
    
    count=0
    IFS="$NL"
    for partdev in $(parted_devices | 
	    sed 's,^/dev/\(ide\|scsi\|[hs]d\),!/dev/\1,' | 
	    sort | 
	    sed 's,^!,,' ); do
	IFS="$TAB"
	set -- $partdev
	dirname=$(echo $1 | sed 's:/:=:g')
	dev=$DEVICES/$dirname
	if [ -d /var/lib/partman/old_devices/$dirname ]; then
	    mv /var/lib/partman/old_devices/$dirname $dev
	else
	    mkdir $dev || continue
	fi
	printf "%s" "$1" >$dev/device
	printf "%s" "$2" >$dev/size
	printf "%s" "$3" >$dev/model
	
	cd $dev
	open_dialog OPEN "$(cat $dev/device)"
	read_line response
	close_dialog
	if [ "$response" = failed ]; then
	    cd /
	    rm -rf $dev
	fi
    done
fi

# The procedure below assumes there is only one disk device!
echo "Scanning devices"

for dev in /var/lib/partman/devices/*; do
    [ -d "$dev" ] || continue
    cd $dev
    partitions=
    open_dialog PARTITIONS
    while { read_line partinfo; [ "$partinfo" ]; }; do
	if [ "$partitions" ]; then
	    partitions="$partitions
$partinfo"
	else
	    partitions="$partinfo"
	fi
    done
    close_dialog
    # Get the ID of the first partition
    IFS="$NL"
    for partinfo in $partitions; do
	restore_ifs
	set -- $partinfo
	CURID="$2"
	break 2	# Don't process other partitions or devices
    done
done

echo "Resizing the first partition"

open_dialog VIRTUAL_RESIZE_PARTITION $CURID 1000000000
read_line NEWID
close_dialog
echo "Old ID: $CURID"
echo "New ID: $NEWID"

open_dialog COMMIT
close_dialog

echo "Closing the server"
stop_parted_server
