grml-chroot: display usage info additionally to wrong number of arguments
[grml-scripts.git] / usr_sbin / grml-chroot
1 #!/bin/bash
2 # Filename:      grml-chroot
3 # Purpose:       Program to chroot into another system
4 # Authors:       grml-team (grml.org), (c) Michael Gebetsroither <gebi@grml.org>
5 # Bug-Reports:   see http://grml.org/bugs/
6 # License:       This file is licensed under the GPL v2.
7 ################################################################################
8
9 PROG_NAME_=$(basename $0)
10 DEST_=""
11 MOUNTED_=""     # all mounted destinations
12 COMMAND_=""     # command to start in chroot
13
14
15 function die
16 {
17     echo "Error: $@" >&2
18     exit 1
19 }
20
21 function printUsage
22 {
23     cat <<EOT
24 Usage: "$PROG_NAME_" NEWROOT [COMMAND....]
25
26 $PROG_NAME_ is a chroot wrapper with proc/sys/pts/dev filesystem handling
27
28 EOT
29 }
30
31 function storeMounts
32 {
33     local to_append_="$1"
34     if [[ $MOUNTED_ == "" ]]; then
35         MOUNTED_="$to_append_"
36     else
37         MOUNTED_="$MOUNTED_ $to_append_"
38     fi
39 }
40
41 function mountit
42 {
43     local type_="$1" # type _or_ src
44     local dest_="$2"
45     local options_="$3"
46
47     local all_options_=""
48
49     if [[ $options_ == "--bind" ]]; then
50         all_options_="--bind $type_"
51     else
52         all_options_="-t $type_ none"
53     fi
54     mount $all_options_ "${DEST_}/$dest_" && storeMounts "$dest_"
55 }
56
57 function umount_all
58 {
59     for i in $MOUNTED_; do
60         umount "${DEST_}/$i"
61     done
62 }
63
64
65 ###
66 ### __MAIN
67 ###
68
69 while getopts "h" opt; do
70     case "$opt" in
71         h) printUsage; exit 0 ;;
72         ?) printUsage; exit 64 ;;
73     esac
74 done
75 shift $(($OPTIND - 1))
76
77 if (( $# < 1 )); then
78     printUsage
79     die "Wrong number of arguments."
80 fi
81
82 DEST_="$1"
83 COMMAND_="${2}"
84
85 if [ ! -d "$DEST_" ]; then
86     die "Target chroot does not exist: $DEST_"
87 fi
88
89
90 mountit "proc"  "proc"
91 mountit "sysfs" "sys"
92 mountit "/dev"   "dev"   "--bind"
93 chroot "$DEST_" $COMMAND_
94 umount_all
95