git init
[tools/sbs.git] / bin / make-ext4
1 #!/bin/sh
2
3 set -x
4 set -e
5
6 PATH="/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin"
7
8 INFILE="$1"
9 SIZE="$2"
10 EXT4_BLOCK_SIZE="$3"
11
12 # As we will write one byte, we have to subtract it from total size
13 SEEK=$(($SIZE - 1))
14
15 if [ $# -ne 3 ]; then
16     echo "usage: $0 FILESYSTEM_TGZ FILESYSTEM_SIZE EXT4_BLOCK_SIZE" >&2
17     exit 1
18 fi
19
20 # Perform sanity checks before we install cleanup handler
21 if test -z "$SUDO_UID"; then
22     echo "$0: error: use sudo to run this script" >&2
23     exit 1
24 fi
25
26 if test "$SUDO_UID" -ne "`stat -c '%u' \"$INFILE\" 2>/dev/null`"; then
27     echo "$0: error: you aren't owner of input file $INFILE" >&2
28     exit 1
29 fi
30
31 cleanup()
32 {
33     if [ $? -ne 0 ]; then
34         test "$OUTFILE" -a -f "$OUTFILE" && rm -f "$OUTFILE" >&2
35     fi
36
37     if test "$MNT"; then
38         if mountpoint -q "$MNT"; then
39             umount "$MNT" >&2
40         fi
41         rmdir "$MNT" >&2 || true
42     fi
43 }
44 trap cleanup 0
45 trap cleanup 1
46 trap cleanup 15
47
48 MNT="`mktemp -d /tmp/make-ext4.mountpoint.XXXXXX 2>/dev/null`"
49 OUTFILE="`mktemp /tmp/make-ext4.filesystem.XXXXXX 2>/dev/null`"
50
51
52 # Create sparse file for filesystem
53 dd if=/dev/zero of="$OUTFILE" bs=1 seek="$SEEK" count=1 >&2
54 mkfs.ext4 -O '^huge_file' -F "$OUTFILE" -b "$EXT4_BLOCK_SIZE" >&2
55
56 mount -o loop "$OUTFILE" "$MNT" >&2
57 tar xlpsfC "$INFILE" "$MNT" >&2
58 umount "$MNT" >&2
59
60 # Allow user to do what he wants with newly created file
61 chown "$SUDO_UID:$SUDO_GID" "$OUTFILE" >&2
62 echo "$OUTFILE"