52e56edb77a3bc1a0acfe72b3c9ea75e75693391
[lunaix-os.git] / lunaix-os / scripts / mkrootfs
1 #!/usr/bin/env bash
2
3 SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
4 WS=$(realpath $SCRIPT_DIR/..)
5 USR="${WS}/usr/build"
6
7 fs="ext2"
8 rootfs="${WS}/lunaix_rootfs.${fs}"
9 size_mb=16
10
11 if [ ! -d "${USR}" ]; then
12     echo "build the user target first!"
13     exit 1
14 fi
15
16 prefix=""
17 if [ ! "$EUID" -eq 0 ]; then
18     echo "==================="
19     echo "   mkrootfs require root privilege to manipulate disk image"
20     echo "   you maybe prompted for password"
21     echo "==================="
22     echo
23     prefix="sudo"
24 fi
25
26 tmp_mnt="$(mktemp -d)"
27
28 function cleanup() {
29     echo "an error occured, reverting..."
30     
31     for arg in "$@"
32     do
33         case "$arg" in
34             "tmpmnt")
35                 echo "revert: ${tmp_mnt}"
36                 ${prefix} rm -rf "${tmp_mnt}"
37             ;;
38             "img")
39                 echo "revert: ${rootfs}"
40                 rm -f "${rootfs}"
41             ;;
42             "mnt")
43                 echo "${prefix} rm umount ${tmp_mnt}"
44             ;;
45         esac
46     done
47     
48     exit 1
49 }
50
51 dd if=/dev/zero of="${rootfs}" count=${size_mb} bs=1M \
52     || cleanup tmpmnt
53
54 ${prefix} mkfs.${fs} -L lunaix-rootfs -r 0 "${rootfs}" \
55     || cleanup tmpmnt img
56
57 ${prefix} mount -o loop "${rootfs}" "${tmp_mnt}" \
58     || cleanup tmpmnt img
59
60 ${prefix} chmod -R o+rwx ${tmp_mnt} \
61     || cleanup tmpmnt img
62
63
64 cd "${tmp_mnt}" || cleanup tmpmnt img
65
66 ${prefix} ${SCRIPT_DIR}/mkrootfs-layout ${tmp_mnt} ${USR}
67
68 has_err=$?
69 if [ "$has_err" -eq 2 ]; then
70     cleanup mnt tmpmnt img
71 fi
72
73 sync -f .
74
75 cd "${WS}" || cleanup
76
77 ${prefix} umount "${tmp_mnt}" || cleanup
78
79 ${prefix} rm -d "${tmp_mnt}" || cleanup
80
81 ${prefix} chmod o+rw ${rootfs} || cleanup
82
83 if [ ! "${has_err:-0}" -eq 0  ]; then
84     echo "done, but with error."
85 else
86     echo "done"
87 fi
88
89 exit 0