#!/bin/bash

#The partition device e.g. /dev/sda1
dev=$1

#The device e.g. /dev/sda
pathLocal=$(echo $dev | sed 's/[0-9]//g')

#The partition number e.g. 1
partNr=$(echo $dev | sed 's/[^0-9]//g')

#Check, if there is a partition number or of the whole disk should be saved
if [ -z $partNr ]
then
	#Get the size of the whole device in MB
	size=$(echo No | parted -m -s "$dev" unit MB print | grep "$dev" | cut -d':' -f2 | sed 's/MB//')
	#Store it in the dd format
	echo "$size+0 records out" > /tmp/m23ImagerSize2
	partclone.dd -F -L /dev/null -c -d -s $dev -o -
	exit 0
fi

#Get the info string for the given partition on the device
info=$(echo No | parted "$pathLocal" -s unit MB print | tr -s '[:blank:]' | sed 's/ /#/g' | sed 's/^#*//g' | grep ^[0-9] | sed 's/,[0-9]*MB//g' | sed 's/MB//g' | grep "^$partNr#")

#Get the file system
fs=$(echo "$info" | cut -d'#' -f6)

if [ -z $fs ]
then
	fs=$(echo "$info" | cut -d'#' -f5 | awk '/primary|extended|logical/ {print(""); exit 0}
{print}')
fi


#Get the size of the partition in MB
size=$(echo "$info" | cut -d'#' -f4)
#Store it in the dd format
echo "$size+0 records out" > /tmp/m23ImagerSize2

#Choose the cloning tool by the file system
if [ $(echo $fs | grep -i -c ext) -gt 0 ]
then
	partclone.extfs -F -L /dev/null -c -d -s $dev -o -
	exit 0
fi

if [ $(echo $fs | grep -i -c reiser) -gt 0 ]
then
	partclone.reiser4 -F -L /dev/null -c -d -s $dev -o -
	exit 0
fi

if [ $(echo $fs | grep -i -c btrfs) -gt 0 ]
then
	partclone.btrfs -F -L /dev/null -c -d -s $dev -o -
	exit 0
fi

if [ $(echo $fs | grep -i -c fat) -gt 0 ]
then
	partclone.fat -F -L /dev/null -c -d -s $dev -o -
	exit 0
fi

if [ $(echo $fs | grep -i -c ntfs) -gt 0 ]
then
	partclone.ntfs -F -L /dev/null -c -d -s $dev -o -
	exit 0
fi

partclone.dd -F -L /dev/null -c -d -s $dev -o -
exit 0