grml-addtun: added -h and bridge add/remove handling
[grml-network.git] / sbin / grml-addtun
1 #!/bin/bash
2 # Filename:      grml-addtun
3 # Purpose:       Program to create tun/tap devices and add them to a bridge
4 # Authors:       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 # grml-addtun [OPTIONS] <tun0> <tun1> ...
9
10 set -e
11 #set -x
12
13 PN_="`basename $0`"
14 OPT_DEL_='false'
15 OPT_USER_=''
16 OPT_GROUP_=''
17 OPT_BRIDGE_=''
18
19
20 function printUsage()
21 {
22     cat <<EOT
23 Usage: "$PN_" [OPTIONS] <tun0> <tun1> ...
24
25 $PN_ creates persistent tun/tap devices and optionally add them to a bridge
26
27 OPTIONS:
28    -d           delete the given tun devices and remove them from the bridge if given
29    -u <user>    this user should be able to use the tun device
30    -g <group>   this group should be able to use the tun device
31    -b <bridge>  if given, all tun/tap devices are added/removed from the bridge
32                     bridge is created if not allready existent
33    -h           this help
34 EOT
35 }
36
37 function fromCmdline()
38 {
39     local action_="$1"
40     shift
41
42     while (( $# != 0 )); do
43         case "$1" in
44             "") continue ;;
45         esac
46         $action_ "$1"
47         shift
48     done
49 }
50
51 function createTun()
52 {
53     local args_=''
54     if [[ $OPT_USER_ != '' ]]; then args_="$args_ -u $OPT_USER_"; fi
55     if [[ $OPT_GROUP_ != '' ]]; then args_="$args_ -u $OPT_GROUP_"; fi
56     tunctl -t "$1" $args_
57     if [[ $OPT_BRIDGE_ != '' ]]; then
58         brctl showmacs "$OPT_BRIDGE_" &>/dev/null || brctl addbr "$OPT_BRIDGE_"
59         brctl addif "$OPT_BRIDGE_" "$1"
60     fi
61 }
62
63 function trashTun()
64 {
65     if [[ $OPT_BRIDGE_ != '' ]]; then
66         brctl delif "$OPT_BRIDGE_" "$1"
67     fi
68     tunctl -d "$1"
69 }
70
71
72 ##
73 # MAIN
74 ##
75
76 while getopts "du:g:b:h" opt; do
77     case "$opt" in
78         d) OPT_DEL_='true' ;;
79         u) OPT_USER_="$OPTARG" ;;
80         g) OPT_GROUP_="$OPTARG" ;;
81         b) OPT_BRIDGE_="$OPTARG" ;;
82         h) printUsage; exit 0 ;;
83         ?) printUsage; exit 1 ;;
84     esac
85 done
86 shift $(($OPTIND - 1))
87
88 if [[ $OPT_DEL_ == 'false' ]]; then
89     if [[ $OPT_BRIDGE_ != '' ]]; then
90         brctl showmacs "$OPT_BRIDGE_" &>/dev/null || brctl addbr "$OPT_BRIDGE_"
91     fi
92     fromCmdline "createTun" "$@"
93 else
94     fromCmdline "trashTun" "$@"
95     if [[ $OPT_BRIDGE_ != '' ]]; then
96         brctl showmacs "$OPT_BRIDGE_" &>/dev/null && brctl delbr "$OPT_BRIDGE_"
97     fi
98 fi
99
100 # vim: filetype=sh