summaryrefslogtreecommitdiffstats
path: root/util/bin/magic
blob: a404c0c30511efea8d3c6c7d1a175aff363dd1be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#! /bin/sh
set -euf

bs="# begin krebs magic <$2>"
es="# end krebs magic <$2>"

has() {
  grep -q "^$bs$" $3 && grep -q "^$es$" $3
}

create() {
  destroy "$@"
  cat>>$3<<EOF
$bs
`cat`
$es
EOF
}

retrieve() {
  sed -n "/^$bs$/,/^$es$/p" $3 | sed '1d;$d'
}

update() {
  ! has "$@" || create "$@"
}

destroy() {
  if has "$@"; then
    cache="`cat $3`"
    echo "$cache" | sed "/^$bs$/,/^$es$/d" >$3
  fi
}
help() {
cat <<EOF
Usage: $0 FUNCTION DELIMITER_NAME FILE
$0 creates,updates or destroys magic inside a file.
It can be used to reliably add or remove custom lines.
For example add own lines in /etc/rc.local to auto-load 
scripts.

FUNCTION:
  create -- creates new magic in file, takes stdin as content in magic
  update -- updates already existing magic with text from stdin
  destroy -- destroys magic boundary
  retrieve -- retrieve the content of magic and writes to stdout
  
Not yet implemented is the handling of magic not starting with the 
shell comment symbol "#".

EOF

}
case $1 in
  (create) create "$@" ;;
  (retrieve) retrieve "$@" ;;
  (update) update "$@" ;;
  (destroy) destroy "$@" ;;
  (*)
    help >&2
    echo 'Error 1: You are made of stupid!' >&2
    exit 23
esac