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