blob: 91b33b9e89a467011456830667c6b416708924af [file] [log] [blame]
Gilles Peskined0a4dc82020-04-23 17:33:36 +02001## Common shell functions used by demo scripts programs/*/*.sh.
2
3## How to write a demo script
4## ==========================
5##
6## Include this file near the top of each demo script:
7## . "${0%/*}/../demo_common.sh"
8##
9## As the last thing in the script, call the cleanup function.
10##
11## You can use the functions and variables described below.
12
13set -e -u
14
15## $root_dir is the root directory of the Mbed TLS source tree.
16root_dir="${0%/*}"
17n=4 # limit the search depth
18while ! [ -d "$root_dir/programs" ] || ! [ -d "$root_dir/library" ]; do
19 if [ $n -eq 0 ]; then
20 echo >&2 "This doesn't seem to be an Mbed TLS source tree."
21 exit 125
22 fi
23 n=$((n - 1))
24 case $root_dir in
25 .) root_dir="..";;
26 ..|?*/..) root_dir="$root_dir/..";;
27 ?*/*) root_dir="${root_dir%/*}";;
28 /*) root_dir="/";;
29 *) root_dir=".";;
30 esac
31done
32
33## $programs_dir is the directory containing the sample programs.
34programs_dir="$root_dir/programs"
35
36## msg LINE...
37## msg <TEXT_ORIGIN
38## Display an informational message.
39msg () {
40 if [ $# -eq 0 ]; then
41 sed 's/^/# /'
42 else
43 for x in "$@"; do
44 echo "# $x"
45 done
46 fi
47}
48
49## run "Message" COMMAND ARGUMENT...
50## Display the message, then run COMMAND with the specified arguments.
51run () {
52 echo
53 echo "# $1"
54 shift
55 echo "+ $*"
56 "$@"
57}
58
59## Like '!', but stop on failure with 'set -e'
60not () {
61 if "$@"; then false; fi
62}
63
64## run_bad "Message" COMMAND ARGUMENT...
65## Like run, but the command is expected to fail.
66run_bad () {
67 echo
68 echo "$1 This must fail."
69 shift
70 echo "+ ! $*"
71 not "$@"
72}
73
74## Add the names of files to clean up to this whitespace-separated variable.
75## The file names must not contain whitespace characters.
76files_to_clean=
77
78
79
80################################################################
81## End of the public interfaces. Code beyond this point is not
82## meant to be called directly from a demo script.
83
84cleanup () {
85 rm -f -- $files_to_clean
86}
87trap 'cleanup; trap - HUP; kill -HUP $$' HUP
88trap 'cleanup; trap - INT; kill -INT $$' INT
89trap 'cleanup; trap - TERM; kill -TERM $$' TERM