ec727f8ba8cbd82292d88406ee8160007b1524b3
[live-build.git] / functions / losetup.sh
1 #!/bin/sh
2
3 ## live-build(7) - System Build Scripts
4 ## Copyright (C) 2006-2013 Daniel Baumann <daniel@debian.org>
5 ##
6 ## This program comes with ABSOLUTELY NO WARRANTY; for details see COPYING.
7 ## This is free software, and you are welcome to redistribute it
8 ## under certain conditions; see COPYING for details.
9
10 Lodetach ()
11 {
12 DEVICE="${1}"
13 ATTEMPT="${2:-1}"
14
15 if [ "${ATTEMPT}" -gt 3 ]
16 then
17 Echo_error "Failed to detach loop device '${DEVICE}'."
18 exit 1
19 fi
20
21 # Changes to block devices result in uevents which trigger rules which in
22 # turn access the loop device (ex. udisks-part-id, blkid) which can cause
23 # a race condition. We call 'udevadm settle' to help avoid this.
24 if [ -x "$(which udevadm 2>/dev/null)" ]
25 then
26 udevadm settle
27 fi
28
29 # Loop back devices aren't the most reliable when it comes to writes.
30 # We sleep and sync for good measure - better than build failure.
31 sync
32 sleep 1
33
34 ${LB_LOSETUP} -d "${DEVICE}" || Lodetach "${DEVICE}" "$(expr ${ATTEMPT} + 1)"
35 }
36
37 Losetup ()
38 {
39 DEVICE="${1}"
40 FILE="${2}"
41 PARTITION="${3:-1}"
42
43 ${LB_LOSETUP} --read-only "${DEVICE}" "${FILE}"
44 FDISK_OUT="$(${LB_FDISK} -l -u ${DEVICE} 2>&1)"
45 Lodetach "${DEVICE}"
46
47 LOOPDEVICE="$(echo ${DEVICE}p${PARTITION})"
48
49 if [ "${PARTITION}" = "0" ]
50 then
51 Echo_message "Mounting %s with offset 0" "${DEVICE}"
52
53 ${LB_LOSETUP} "${DEVICE}" "${FILE}"
54 else
55 SECTORS="$(echo "$FDISK_OUT" | sed -ne "s|^$LOOPDEVICE[ *]*\([0-9]*\).*|\1|p")"
56 OFFSET="$(expr ${SECTORS} '*' 512)"
57
58 Echo_message "Mounting %s with offset %s" "${DEVICE}" "${OFFSET}"
59
60 ${LB_LOSETUP} -o "${OFFSET}" "${DEVICE}" "${FILE}"
61 fi
62 }
63
64 Calculate_partition_size ()
65 {
66 ORIGINAL_SIZE="${1}"
67 FILESYSTEM="${2}"
68
69 case "${FILESYSTEM}" in
70 ext2|ext3|ext4)
71 PERCENT="6"
72 ;;
73 *)
74 PERCENT="3"
75 ;;
76 esac
77
78 echo $(expr ${ORIGINAL_SIZE} + ${ORIGINAL_SIZE} \* ${PERCENT} / 100 + 1)
79 }