summaryrefslogtreecommitdiff
path: root/scripts/contrib/ddimage
blob: a503f11d0dd8e4d83f1aa012cd813382c2a8f0e9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#!/bin/sh

# Default to avoiding the first two disks on typical Linux and Mac OS installs
# Better safe than sorry :-)
BLACKLIST_DEVICES="/dev/sda /dev/sdb /dev/disk1 /dev/disk2"

# 1MB blocksize
BLOCKSIZE=1048576

usage() {
	echo "Usage: $(basename $0) IMAGE DEVICE"
}

image_details() {
	IMG=$1
	echo "Image details"
	echo "============="
	echo "    image: $(basename $IMG)"
	# stat format is different on Mac OS and Linux
	if [ "$(uname)" = "Darwin" ]; then
		echo "     size: $(stat -L -f '%z bytes' $IMG)"
		echo " modified: $(stat -L -f '%Sm' $IMG)"
	else
		echo "     size: $(stat -L -c '%s bytes' $IMG)"
		echo " modified: $(stat -L -c '%y' $IMG)"
	fi
	echo "     type: $(file -L -b $IMG)"
	echo ""
}

device_details() {
	DEV=$1
	BLOCK_SIZE=512

	echo "Device details"
	echo "=============="

	# Collect disk info using diskutil on Mac OS
	if [ "$(uname)" = "Darwin" ]; then
		diskutil info $DEVICE | egrep "(Device Node|Media Name|Total Size)"
		return
	fi

	# Default / Linux information collection
	echo "  device: $DEVICE"
	if [ -f "/sys/class/block/$DEV/device/vendor" ]; then
		echo "  vendor: $(cat /sys/class/block/$DEV/device/vendor)"
	else
		echo "  vendor: UNKOWN"
	fi
	if [ -f "/sys/class/block/$DEV/device/model" ]; then
		echo "   model: $(cat /sys/class/block/$DEV/device/model)"
	else
		echo "   model: UNKNOWN"
	fi
	if [ -f "/sys/class/block/$DEV/size" ]; then
		echo "    size: $(($(cat /sys/class/block/$DEV/size) * $BLOCK_SIZE)) bytes"
	else
		echo "    size: UNKNOWN"
	fi
	echo ""
}

if [ $# -ne 2 ]; then
	usage
	exit 1
fi

IMAGE=$1
DEVICE=$2

if [ ! -e "$IMAGE" ]; then
	echo "ERROR: Image $IMAGE does not exist"
	usage
	exit 1
fi


for i in ${BLACKLIST_DEVICES}; do
	if [ "$i" = "$DEVICE" ]; then
		echo "ERROR: Device $DEVICE is blacklisted"
		exit 1
	fi
done

if [ ! -w "$DEVICE" ]; then
	echo "ERROR: Device $DEVICE does not exist or is not writable"
	usage
	exit 1
fi

image_details $IMAGE
device_details $(basename $DEVICE)

printf "Write $IMAGE to $DEVICE [y/N]? "
read RESPONSE
if [ "$RESPONSE" != "y" ]; then
	echo "Write aborted"
	exit 0
fi

echo "Writing image..."
dd if="$IMAGE" of="$DEVICE" bs="$BLOCKSIZE"
sync