fix various variable copying bugs
[openwrt/svn-archive/archive.git] / package / base-files / default / etc / functions.sh
1 #!/bin/sh
2 # Copyright (C) 2006 OpenWrt.org
3 # Copyright (C) 2006 Fokus Fraunhofer <carsten.tittel@fokus.fraunhofer.de>
4
5 alias debug=${DEBUG:-:}
6
7 # newline
8 N="
9 "
10
11 _C=0
12
13 hotplug_dev() {
14 env -i ACTION=$1 INTERFACE=$2 /sbin/hotplug net
15 }
16
17 append() {
18 local var="$1"
19 local value="$2"
20 local sep="${3:- }"
21
22 eval "$var=\"\${$var:+\${$var}\${value:+\$sep}}\$value\""
23 }
24
25 reset_cb() {
26 config_cb() { return 0; }
27 option_cb() { return 0; }
28 }
29 reset_cb
30
31 config () {
32 local cfgtype="$1"
33 local name="$2"
34
35 _C=$((_C + 1))
36 name="${name:-cfg${_C}}"
37 config_cb "$cfgtype" "$name"
38 CONFIG_SECTION="$name"
39 eval CONFIG_${CONFIG_SECTION}_TYPE="\$cfgtype"
40 }
41
42 option () {
43 local varname="$1"; shift
44 local value="$*"
45
46 eval CONFIG_${CONFIG_SECTION}_${varname}="\$value"
47 option_cb "$varname" "$*"
48 }
49
50 config_rename() {
51 local OLD="$1"
52 local NEW="$2"
53 local oldvar
54 local newvar
55
56 [ "$OLD" -a "$NEW" ] || return
57 for oldvar in `set | grep ^CONFIG_${OLD}_ | \
58 sed -e 's/\(.*\)=.*$/\1/'` ; do
59 newvar="CONFIG_${NEW}_${oldvar##CONFIG_${OLD}_}"
60 eval "$newvar=\${$oldvar}"
61 unset "$oldvar"
62 done
63
64 [ "$CONFIG_SECTION" = "$OLD" ] && CONFIG_SECTION="$NEW"
65 }
66
67 config_unset() {
68 config_set "$1" "$2" ""
69 }
70
71 config_clear() {
72 local SECTION="$1"
73 local oldvar
74
75 for oldvar in `set | grep ^CONFIG_${SECTION}_ | \
76 sed -e 's/\(.*\)=.*$/\1/'` ; do
77 unset $oldvar
78 done
79 }
80
81 config_load() {
82 local file="/etc/config/$1"
83 _C=0
84 CONFIG_SECTION=
85
86 [ -e "$file" ] && {
87 . $file
88 } || return 1
89
90 ${CONFIG_SECTION:+config_cb}
91 }
92
93 config_get() {
94 case "$3" in
95 "") eval "echo \"\${CONFIG_${1}_${2}}\"";;
96 *) eval "$1=\"\${CONFIG_${2}_${3}}\"";;
97 esac
98 }
99
100 config_set() {
101 local section="$1"
102 local option="$2"
103 local value="$3"
104 eval CONFIG_${section}_${option}="\$value"
105 }
106
107 load_modules() {
108 sed 's/^[^#]/insmod &/' $* | ash 2>&- || :
109 }
110
111 include() {
112 local file
113
114 for file in $(ls $1/*.sh 2>/dev/null); do
115 . $file
116 done
117 }
118
119 find_mtd_part() {
120 local PART="$(grep "\"$1\"" /proc/mtd | awk -F: '{print $1}')"
121
122 PART="${PART##mtd}"
123 echo "${PART:+/dev/mtdblock/$PART}"
124 }
125
126 strtok() { # <string> { <variable> [<separator>] ... }
127 local tmp
128 local val="$1"
129 local count=0
130
131 shift
132
133 while [ $# -gt 1 ]; do
134 tmp="${val%%$2*}"
135
136 [ "$tmp" = "$val" ] && break
137
138 val="${val#$tmp$2}"
139
140 eval $1="\$tmp"; count=$((count+1))
141 shift 2
142 done
143
144 if [ $# -gt 0 -a "$val" ]; then
145 eval $1="\$val"; count=$((count+1))
146 fi
147
148 return $count
149 }