summaryrefslogtreecommitdiffstats
path: root/write_flash.sh
blob: 4a26e5a865b36004d75a3198131256893ab13b27 (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
#!/bin/sh

source=mandriva-linux-flash-2010-KDE4-all-usb-i586.img
dump_block_size=$((2*1024*1024))

title="USB image dump"

image_size=$(stat -c %s $source)
image_md5=$(awk '{ print $1 }' $source.md5)
mbr_size=512

image_blocks=$((image_size/dump_block_size))
image_remainder_bytes=$((image_size%dump_block_size))
image_remainder_skip=$((image_size-image_remainder_bytes))

log() {
    echo "$* (on $(date))"
}

show_wait() {
    log $*
    zenity --progress --auto-kill --title "$title" --text "$*" &
}

show_progress() {
    log $*
    zenity --progress --auto-kill --pulsate --title "$title" --text "$*" &
}

show_error() {
    log $*
    zenity --error --title $title --text "$*"
}

# forbid auto-mount on LXDE
killall halevt

#mkdir -p /mnt/loop
#mount -o offset=$((62*512)),ro $source /mnt/loop
while true; do
 show_wait "Please insert new key"
 wait_pid=$!
 while sleep 5; do
  dev=$(grep 'sd[^a]$' /proc/partitions | awk '{ print $4 }')
  if [ -n "$dev" ]; then
      dest=/dev/$dev
      break
  fi
 done

 sleep 2
 grep "^$dest" /proc/mounts | awk '{ print $1 }' | xargs -r umount
 kill $wait_pid

 show_progress "Key found, writing image"
 wait_pid=$!

 dd if=$source of=$dest bs=$dump_block_size
 kill $wait_pid
 if [ $? -ne 0 ]; then
     show_error "Key dump failed"
     exit 1
 fi

 #- more optimized write method, but harder to check
 #dd if=$source of=$dest count=$mbr_size
 #blockdev --rereadpt $dest
 #mkdir -p /mnt/disk
 #mount ${dest}1 /mnt/disk
 #rsync -avP /mnt/loop /mnt/disk
 #umount /mnt/disk

 show_progress "Key dumped, checking"
 wait_pid=$!
 sync

 dumped_md5=$((dd if=$dest bs=$dump_block_size count=$image_blocks; dd if=$dest bs=1 skip=$image_remainder_skip count=$image_remainder_bytes) | md5sum - | awk '{ print $1 }')
 kill $wait_pid

 echo "md5: dumped = $dumped_md5"
 echo "md5: source = $image_md5"
 if [ "$dumped_md5" != "$image_md5" ]; then
     show_error "Key has errors"
     exit 1
 fi
 show_wait "Key dumped and verified"$'\n'$'\n'"Please remove key"
 wait_pid=$!

 while sleep 5; do
  grep -q 'sd[^a]$' /proc/partitions || break
 done
 kill $wait_pid
 echo "Key removed"
done
#umount /mnt/loop