Revision 0a42f078

View differences:

compiler/GCC/gccsetup.sh
1
################################################################################
2
# AMiRo-BLT is an bootloader and toolchain designed for the Autonomous Mini    #
3
# Robot (AMiRo) platform.                                                      #
4
# Copyright (C) 2016..2017  Thomas Schöpping et al.                            #
5
#                                                                              #
6
# This program is free software: you can redistribute it and/or modify         #
7
# it under the terms of the GNU General Public License as published by         #
8
# the Free Software Foundation, either version 3 of the License, or            #
9
# (at your option) any later version.                                          #
10
#                                                                              #
11
# This program is distributed in the hope that it will be useful,              #
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of               #
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                #
14
# GNU General Public License for more details.                                 #
15
#                                                                              #
16
# You should have received a copy of the GNU General Public License            #
17
# along with this program.  If not, see <http://www.gnu.org/licenses/>.        #
18
#                                                                              #
19
# This research/work was supported by the Cluster of Excellence Cognitive      #
20
# Interaction Technology 'CITEC' (EXC 277) at Bielefeld University, which is   #
21
# funded by the German Research Foundation (DFG).                              #
22
################################################################################
23

  
24
#!/bin/bash
25

  
26
################################################################################
27
# GENERIC FUNCTIONS                                                            #
28
################################################################################
29

  
30
### print an error message #####################################################
31
# Prints a error <message> to standard output.
32
#If variable 'LOG_FILE' is specified, the message is also appended to the given file.
33
#
34
# usage:      printError <message>
35
# arguments:  <message>
36
#                 Message string to print.
37
# return:     n/a
38
#
39
function printError {
40
  local string="ERROR:   $1"
41
  # if a log file is specified
42
  if [ -n "$LOG_FILE" ]; then
43
    printf "[$(date '+%Y-%m-%d %H:%M:%S')] $string" >> $LOG_FILE
44
  fi
45
  printf "$(tput setaf 1)>>> $string$(tput sgr 0)" 1>&2
46
}
47

  
48
### print a warning message ####################################################
49
# Prints a warning <message> to standard output.
50
#If variable 'LOG_FILE' is specified, the message is also appended to the given file.
51
#
52
# usage:      printMessage <message>
53
# arguments:  <message>
54
#                 Message string to print.
55
# return:     n/a
56
#
57
function printWarning {
58
  local string="WARNING: $1"
59
  # if a log file is specified
60
  if [ -n "$LOG_FILE" ]; then
61
    printf "[$(date '+%Y-%m-%d %H:%M:%S')] $string" >> $LOG_FILE
62
  fi
63
  printf "$(tput setaf 3)>>> $string$(tput sgr 0)"
64
}
65

  
66
### print an information message ###############################################
67
# Prints an information <message> to standard output.
68
#If variable 'LOG_FILE' is specified, the message is also appended to the given file.
69
#
70
# usage:      printInfo <message>
71
# arguments:  <message>
72
#                 Message string to print.
73
# return:     n/a
74
#
75
function printInfo {
76
  local string="INFO:    $1"
77
  # if a log file is specified
78
  if [ -n "$LOG_FILE" ]; then
79
    printf "[$(date '+%Y-%m-%d %H:%M:%S')] $string" >> $LOG_FILE
80
  fi
81
  printf "$(tput setaf 2)>>> $string$(tput sgr 0)"
82
}
83

  
84
### print a message to file ####################################################
85
# Appends a <message> to a log file, specified by the variable 'LOG_FILE'.
86
#
87
# usage       printLog <message>
88
# arguments:  <message>
89
#                 Message string to print.
90
# return:     n/a
91
#
92
function printLog {
93
  local string="LOG:     $1"
94
  # if a log file is specified
95
  if [ -n "$LOG_FILE" ]; then
96
    printf "[$(date '+%Y-%m-%d %H:%M:%S')] $string" >> $LOG_FILE
97
  fi
98
}
99

  
100
### exit the script normally ###################################################
101
# Prints a delimiter and exits the script normally (returns 0).
102
#
103
# usage:      quitScript
104
# arguments:  n/a
105
# return:     0
106
#                 No error or warning occurred.
107
#
108
function quitScript {
109
  printLog "exiting $(realpath ${BASH_SOURCE[0]})\n"
110
  printf "######################################################################\n"
111
  exit 0
112
}
113

  
114
### read a user input ##########################################################
115
# Reads a single character user input from a set up <options> and stores it in
116
# a given <return> variable.
117
#
118
# usage:      readUserInput <options> <return>
119
# arguments:  <options>
120
#                 String definiing the set of valid characters.
121
#                 If the string is empty, the user can input any character.
122
#             <return>
123
#                 Variable to store the selected character to.
124
# return:     n/a
125
#
126
function readUserInput {
127
  local input=""
128
  # read user input
129
  while [ -z $input ] || ( [ -n "$1" ] && [[ ! $input =~ ^[$1]$ ]] ); do
130
    read -p "your selection: " -n 1 -e input
131
    if [ -z $input ] || ( [ -n "$1" ] && [[ ! $input =~ ^[$1]$ ]] ); then
132
      printWarning "[$input] is no valid action\n"
133
    fi
134
  done
135
  printLog "[$input] has been selected\n"
136
  eval $2="$input"
137
}
138

  
139
### check whether argument is an option ########################################
140
# Checks a <string> whether it is an option.
141
# Options are defined to either start with '--' followed by any string, or
142
# to start with a single '-' followed by a single character, or
143
# to start with a single '-' followed by a single character, a '=' and any string.
144
# Examples: '--option', '--option=arg', '-o', '-o=arg', '--'
145
#
146
# usage:      parseIsOption <string>
147
# arguments:  <string>
148
#                 A string to check whether it is an option.
149
# return:     0
150
#                 <string> is an option.
151
#             -1
152
#                 <string> is not an option.
153
#
154
function parseIsOption {
155
  if [[ "$1" =~ ^-(.$|.=.*) ]] || [[ "$1" =~ ^--.* ]]; then
156
    return 0
157
  else
158
    return -1
159
  fi
160
}
161

  
162
### set the log file ###########################################################
163
# Sets a specified <infile> as log file and checks whether it already exists.
164
# If so, the log may either be appended to the file, its content can be cleared,
165
# or no log is generated at all.
166
# The resulting path is stored in <outvar>.
167
#
168
# usage:      setLogFile [--option=<option>] [--quiet] <infile> <outvar>
169
# arguments:  --option=<option>
170
#                 Select what to do if <file> already exists.
171
#                 Possible values are 'a', 'r' and 'n'.
172
#                 - a: append
173
#                 - r: delete and restart
174
#                 - n: no log
175
#                 If no option is secified but <file> exists, an interactive selection is provided.
176
#             --quiet
177
#                 Suppress all messages.
178
#             <infile>
179
#                 Path of the wanted log file.
180
#             <outvar>
181
#                 Variable to store the path of the log file to.
182
# return:     0
183
#                 No error or warning occurred.
184
#             -1
185
#                 Error: invalid input
186
#
187
function setLogFile {
188
  local filepath=""
189
  local option=""
190
  local quiet=false
191

  
192
  # parse arguments
193
  local otherargs=()
194
  while [ $# -gt 0 ]; do
195
    if ( parseIsOption $1 ); then
196
      case "$1" in
197
        -o=*|--option=*)
198
          option=${1#*=}; shift 1;;
199
        -o*|--option*)
200
          option="$2"; shift 2;;
201
        -q|--quiet)
202
          quiet=true; shift 1;;
203
        *)
204
          printError "invalid option: $1\n"; shift 1;;
205
      esac
206
    else
207
      otherargs+=("$1")
208
      shift 1
209
    fi
210
  done
211
  filepath=$(realpath ${otherargs[0]})
212

  
213
  # if file already exists
214
  if [ -e $filepath ]; then
215
    # if no option was specified, ask what to do
216
    if [ -z "$option" ]; then
217
      printWarning "log file $filepath already esists\n"
218
      local userinput=""
219
      printf "Select what to do:\n"
220
      printf "  [A] - append log\n"
221
      printf "  [R] - restart log (delete existing file)\n"
222
      printf "  [N] - no log\n"
223
      readUserInput "AaRrNn" userinput
224
      option=${userinput,,}
225
    fi
226
    # evaluate option
227
    case "$option" in
228
      a)
229
        if [ $quiet = false ]; then
230
          printInfo "appending log to $filepath\n"
231
        fi
232
        printf "\n" >> $filepath
233
        printf "######################################################################\n" >> $filepath
234
        printf "\n" >> $filepath
235
        ;;
236
      r)
237
        echo -n "" > $filepath
238
        if [ $quiet = false ]; then
239
          printInfo "content of $filepath wiped\n"
240
        fi
241
        ;;
242
      n)
243
        if [ $quiet = false ]; then
244
          printInfo "no log file will be generated\n"
245
        fi
246
        filepath=""
247
        ;;
248
      *) # sanity check (return error)
249
        printError "unexpected argument: $option\n"; return -1;;
250
    esac
251
  else
252
    if [ $quiet = false ]; then
253
      printInfo "log file set to $filepath\n"
254
    fi
255
  fi
256

  
257
  eval ${otherargs[1]}="$filepath"
258

  
259
  return 0
260
}
261

  
262
################################################################################
263
# SPECIFIC FUNCTIONS                                                           #
264
################################################################################
265

  
266
### print welcome text #########################################################
267
# Prints a welcome message to standard out.
268
#
269
# usage:      printWelcomeText
270
# arguments:  n/a
271
# return:     n/a
272
#
273
function printWelcomeText {
274
  printf "######################################################################\n"
275
  printf "#                                                                    #\n"
276
  printf "#                     Welcome to the GCC setup!                      #\n"
277
  printf "#                                                                    #\n"
278
  printf "######################################################################\n"
279
  printf "#                                                                    #\n"
280
  printf "# Copyright (c) 2016..2017  Thomas Schöpping                         #\n"
281
  printf "#                                                                    #\n"
282
  printf "# This is free software; see the source for copying conditions.      #\n"
283
  printf "# There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR  #\n"
284
  printf "# A PARTICULAR PURPOSE. The development of this software was         #\n"
285
  printf "# supported by the Excellence Cluster EXC 227 Cognitive Interaction  #\n"
286
  printf "# Technology. The Excellence Cluster EXC 227 is a grant of the       #\n"
287
  printf "# Deutsche Forschungsgemeinschaft (DFG) in the context of the German #\n"
288
  printf "# Excellence Initiative.                                             #\n"
289
  printf "#                                                                    #\n"
290
  printf "######################################################################\n"
291
}
292

  
293
### print help #################################################################
294
# Prints a help text to standard out.
295
#
296
# usage:      printHelp
297
# arguments:  n/a
298
# return:     n/a
299
#
300
function printHelp {
301
  printInfo "printing help text\n"
302
  printf "usage:    $(basename ${BASH_SOURCE[0]}) [-h|--help] [-i|--install] [-c|--change] [-q|--quit] [--log=<file>]\n"
303
  printf "\n"
304
  printf "options:  -h, --help\n"
305
  printf "              Print this help text.\n"
306
  printf "          -i, --install\n"
307
  printf "              Install another version.\n"
308
  printf "          -c, --change\n"
309
  printf "              Change the default version.\n"
310
  printf "          -q, --quit\n"
311
  printf "              Quit the script.\n"
312
  printf "          --log=<file>\n"
313
  printf "              Specify a log file.\n"
314
}
315

  
316
### detect installed versions ##################################################
317
# Detect all installed version of arm-none-eabi-gcc, if any.
318
#
319
# usage:      detectInstalledVersions <binarray> <current>
320
# arguments:  <binarray>
321
#                 Array variable to store all detected binary paths to. 
322
#             <current>
323
#                 Variable to store the currently active binary to.
324
# return:     n/a
325
#
326
function detectInstalledVersions {
327
  local armgcc_command=$(command -v arm-none-eabi-gcc)
328
  local armgcc_commanddir=${HOME}/gcc-none-eabi
329
  local armgcc_currentbin=""
330
  local armgcc_installdir=${HOME}/gcc-none-eabi
331
  local armgcc_bins=()
332
  local armgcc_bincnt=0
333

  
334
  # check for already installed versions
335
  if [ -n "$armgcc_command" ]; then
336
    # follow the link to the actual binary
337
    armgcc_commanddir=$(dirname $armgcc_command)
338
    armgcc_currentbin=$armgcc_command
339
    while [ -L $armgcc_currentbin ]; do
340
      armgcc_currentbin=$(readlink $armgcc_currentbin)
341
    done
342
    # the installation location is assumed to be two directories up
343
    armgcc_installdir=$(realpath $(dirname ${armgcc_currentbin})/../../)
344
    # list all detected instalations
345
    for dir in $(ls -d ${armgcc_installdir}/*/); do
346
      if [ -f ${dir}/bin/arm-none-eabi-gcc ]; then
347
        armgcc_bins[$armgcc_bincnt]=${dir}bin/arm-none-eabi-gcc
348
        armgcc_bincnt=$((armgcc_bincnt + 1))
349
      fi
350
    done
351
  fi
352

  
353
  eval "$1=(${armgcc_bins[*]})"
354
  eval $2="$armgcc_currentbin"
355
}
356

  
357
### install new version ########################################################
358
# Fetches an installation package from the internet, installs it and expands
359
# the $PATH environment variable (via .bashrc) if required.
360
#
361
# usage:      installNewVersion [-i|--install=<path>] [-l|--link=<path>]
362
# argumenst:  -i, --install <path>
363
#                 Path where to install the new version to.
364
#             -l, --link <path>
365
#                 Path where to create according links.
366
# return:     0
367
#                 No error or warnign occurred.
368
#             1
369
#                 Warning: Installation aborted by user.
370
#
371
function installNewVersion {
372
  local installbasedir=${HOME}/gcc-arm-embedded
373
  local linkdir="/usr/bin"
374

  
375
  # parse arguments
376
  local otherargs=()
377
  while [ $# -gt 0 ]; do
378
    if ( parseIsOption $1 ); then
379
      case "$1" in
380
        -i=*|--install=*)
381
          installbasedir=$(realpath "${1#*=}"); shift 1;;
382
        -i|--install)
383
          installbasedir="$2"; shift 2;;
384
        -l=*|--link=*)
385
          linkdir=$(realpath "${1#*=}"); shift 1;;
386
        -l|--link)
387
          linkdir="$2"; shift 2;;
388
        *) # sanity check (exit with error)
389
          printError "invalid option: $1\n"; shift 1;;
390
      esac
391
    else
392
      otherargs+=("$1")
393
      shift 1
394
    fi
395
  done
396

  
397
  # read download URL form user
398
  printLog "read installation url from user\n"
399
  local armgcc_downloadurl=""
400
  while [[ "$armgcc_downloadurl" != *".tar.bz2" ]]; do
401
    read -p "Download link for the installation file: " -e armgcc_downloadurl
402
    if [[ $armgcc_downloadurl != *".tar.bz2" ]]; then
403
      printWarning "please specify a .tar.bz2 file\n"
404
    fi
405
  done
406
  printLog "user selected $armgcc_downloadurl\n"
407

  
408
  # if the file already exists, ask the user if it should be downloaded again
409
  local armgcc_tarball=$(basename "$armgcc_downloadurl")
410
  if [ -e "$armgcc_tarball" ]; then
411
    printWarning "$armgcc_tarball already exists. Delete and redownload? [y/n]\n"
412
    local userinput=""
413
    readUserInput "YyNn" userinput
414
    case "$userinput" in
415
      Y|y)
416
        rm "$armgcc_tarball"
417
        wget "$armgcc_downloadurl" | tee -a $LOG_FILE
418
        ;;
419
      N|n)
420
        ;;
421
      *) # sanity check (exit with error)
422
        printError "unexpected argument: $userinput\n";;
423
    esac
424
  else
425
    wget "$armgcc_downloadurl" | tee -a $LOG_FILE
426
  fi
427

  
428
  # extract tarball
429
  printInfo "extracting ${armgcc_tarball}...\n"
430
  tar -jxf "$armgcc_tarball" | tee -a $LOG_FILE
431
  local compilerdir=`tar --bzip2 -tf ${armgcc_tarball} | sed -e 's@/.*@@' | uniq`
432

  
433
  # install gcc arm mebedded
434
  printLog "read installation directory from user\n"
435
  local installdir=""
436
  read -p "Installation directory: " -i ${installbasedir}/${compilerdir} -e installdir
437
  printLog "user selected $installdir\n"
438
  printLog "read link directory\n"
439
  read -p "Link directory: " -i $linkdir -e linkdir
440
  printLog "user selected $linkdir\n"
441
  # if the installation path already exists, ask user to overwrite
442
  if [ -d "$installdir" ]; then
443
    printWarning "$installdir already exists. Overwrite? [y/n]\n"
444
    local userinput=""
445
    readUserInput "YyNn" userinput
446
    case "$userinput" in
447
      Y|y)
448
        ;;
449
      N|n)
450
        printWarning "installation aborted by user\n"
451
        return 1
452
        ;;
453
      *) # sanity check (exit with error)
454
        printError "invalid option: $userinput\n";;
455
    esac
456
  # make sure the whole ínstallation path exists
457
  else
458
    echo "$installdir path not exist"
459
    while [ ! -d $(dirname "$installdir") ]; do
460
      local dir=$(dirname "$installdir") 
461
      while [ ! -d $(dirname "$dir") ]; do
462
        dir=$(dirname "$dir")
463
      done
464
      echo "mkdir $dir"
465
      mkdir "$dir"
466
    done
467
  fi
468
  # copy the extracted compiler folder
469
  cp -fR "$compilerdir" "$installdir"
470
  # make sure whole link path exists
471
  while [ ! -d "$linkdir" ]; do
472
    local dir="$linkdir"
473
    while [ ! -d $(dirname "$linkdir") ]; do
474
      dir=$(dirname "$dir")
475
    done
476
    mkdir "$dir"
477
  done
478
  # create / overwrite links
479
  ls ${installdir}/bin/ | xargs -i ln -sf ${installdir}/bin/{} ${linkdir}/{}
480
  printInfo "default version set to $(arm-none-eabi-gcc -dumpversion)\n"
481

  
482
  read -p "bashrc stuff"
483

  
484
  # append the link directory to the PATH environment variable if required
485
  if [[ ! "$linkdir" = *"$PATH"* ]]; then
486
    local bashrc_file=${HOME}/.bashrc
487
    local bashrc_identifier="##### AMiRo ENVIRONMENT CONFIGURATION #####"
488
    local bashrc_note="# DO NOT EDIT THESE LINES MANUALLY!"
489
    local bashrc_entry="export PATH=\$PATH:$linkdir"
490

  
491
    # find and edit old entry, or append a new one to the file
492
    local bashrc_idlines=$(grep -x -n "$bashrc_identifier" "$bashrc_file" | cut -f1 -d:) # string of line numbers
493
    bashrc_idlines=(${bashrc_idlines//"\n"/" "}) # array of line numbers
494
    case ${#bashrc_idlines[@]} in
495

  
496
      # append a new entry to the BASHRC_FILE
497
      0)
498
        # make sure the last line is empty
499
        if [[ ! $(tail -1 $bashrc_file) =~ ^[\ \t]*$ ]]; then
500
          printf "\n" >> $bashrc_file
501
        fi
502
        # append text to file
503
        sed -i '$a'"$bashrc_identifier\n$bashrc_note\n$bashrc_entry\n$bashrc_identifier\n" $bashrc_file
504
        # print note
505
        printInfo "Your $bashrc_file has been updated. You need to source it to apply the changes in your environment.\n"
506
        read -p "  Understood!"
507
        ;;
508

  
509
      # extend the old entry
510
      2)
511
        # don't do anything if the line is already present
512
        local bashrc_entrylines=$(grep -x -n "$bashrc_entry" $bashrc_file | cut -f1 -d:) # string of line numbers
513
        bashrc_entrylines=(${bashrc_entrylines//"\n"/" "}) # array of line numbers
514
        printf "$bashrc_entrylines\n"
515
        if [[ ${#bashrc_entrylines[@]} = 0 ]]; then
516
          # insert the entry before the closing identifier
517
          sed -i "${bashrc_idlines[1]}"'i'"$bashrc_entry" $bashrc_file
518
          # print note
519
          printInfo "Your $bashrc_file has been updated. You need to source it to apply the changes in your environment.\n"
520
          read -p "  Understood!"
521
        elif [[ ${#bashrc_entrylines[@]} -eq 1 && ( ${bashrc_entrylines[0]} -lt ${bashrc_idlines[0]} || ${bashrc_entrylines[0]} -gt ${bashrc_idlines[1]} ) ]]; then
522
          # print an error that there is an entry at the wrong place
523
          printError "corrupted entry in your $bashrc_file detected\n"
524
          printf "The following entry was found at the wrong place:\n"
525
          printf "\n"
526
          printf "$bashrc_entry\n"
527
          printf "\n"
528
          printf "To fix this, delete the line and rerun this setup.\n"
529
          read -p "  Understood!"
530
        elif [[ ${#bashrc_entrylines[@]} -gt 1 ]]; then
531
          # print an error that there are multiple entries
532
          printError "corrupted entry in your $bashrc_file detected\n"
533
          printf "There are multiple identical entries in your $bashrc_file file.\n"
534
          printf "To fix it, make sure that it contains the following line exactly once:\n"
535
          printf "\n"
536
          printf "$bashrc_entry\n"
537
          printf "\n"
538
          read -p "  Understood!"
539
        fi
540
        ;;
541

  
542
      # error state (corrupted entry detected)
543
      *)
544
        printError "unable to append link directory to \$PATH variable\n"
545
        printf "There seems to be a broken entry in your $bashrc_file file.\n"
546
        printf "To fix it, make sure that the following line appears exactly twice and encloses your AMiRo related settings:\n"
547
        printf "\n"
548
        printf "$bashrc_identifier\n"
549
        printf "\n"
550
        read -p "  Understood!"
551
        ;;
552
    esac
553
  fi
554

  
555
  # clean up the current directory
556
  rm "$armgcc_tarball"
557
  rm -rf "$compilerdir"
558

  
559
  return 0
560
}
561

  
562
### change default version #####################################################
563
# Change the default arm-none-eabi-gcc version.
564
#
565
# usage:      installNewVersion <versions> <linkdir>
566
# argumenst:  <versions>
567
#                 Array of available versions (full path to binary).
568
#             <linkdir>
569
#                 Path where to delete old and create new links.
570
# return:     0
571
#                 No error or warnign occurred.
572
#             -1
573
#                 Error: no installation detected.
574
#
575
function changeDefaultVersion {
576
  local versions=("${!1}")
577
  local linkdir="$2"
578

  
579
  # check whether an installation was detected
580
  if [ ${#versions[@]} -eq 0 ]; then
581
    printError "no installation detected\n"
582
    return -1
583
  else
584
    # print all available versions
585
    printInfo "choose the installation to switch to or type 'A' to abort:\n"
586
    for (( cnt=0; cnt<${#versions[@]}; ++cnt )); do
587
      printf "  %2u: %s\n" $(($cnt + 1)) ${versions[$cnt]}
588
    done
589

  
590
    # read user selection
591
    printLog "read user slection\n"
592
    local userinput=""
593
    while [[ ! "$userinput" =~ ^[0-9]+$ ]] || [ ! "$userinput" -gt 0 ] || [ ! "$userinput" -le ${#versions[@]} ] && [[ ! "$userinput" =~ ^[Aa]$ ]]; do
594
      read -p "your selection: " -e userinput
595
      printLog "user selection: $userinput\n"
596
      if [[ ! "$userinput" =~ ^[0-9]+$ ]] || [ ! "$userinput" -gt 0 ] || [ ! "$userinput" -le ${#versions[@]} ] && [[ ! "$userinput" =~ ^[Aa]$ ]]; then
597
        printWarning "Please enter an integer between 1 and ${#versions[@]} or 'A' to abort.\n"
598
      fi
599
    done
600

  
601
    if [[ "$userinput" =~ ^[Aa]$ ]]; then
602
      printWarning "aborted by user\n"
603
    else
604
      local idx=$((userinput - 1))
605
      # find and delete old links
606
      rm `find $linkdir -maxdepth 1 -type l | grep -Ev "*[0-9]\.[0-9]\.[0-9]"`
607
      # create new links
608
      local bindir=$(dirname ${versions[$idx]})
609
      ls $bindir | xargs -i ln -sf $bindir/{} $linkdir/{}
610
      printInfo "default version set to $(arm-none-eabi-gcc -dumpversion)\n"
611
    fi
612
  fi
613

  
614
  return 0
615
}
616

  
617
### main function of this script ###############################################
618
# The IDE setup lets the user select an IDE of choice.
619
# As of now, only QtCreator is supported.
620
#
621
# usage:      see function printHelp
622
# arguments:  see function printHelp
623
# return:     0
624
#                 No error or warning occurred.
625
#
626
function main {
627
  # print welcome/info text if not suppressed
628
  if [[ $@ != *"--noinfo"* ]]; then
629
    printWelcomeText
630
  else
631
    printf "######################################################################\n"
632
  fi
633
  printf "\n"
634

  
635
  # set log file if specified
636
  if [[ $@ == *"--log"* ]] || [[ $@ == *"--LOG"* ]]; then
637
    # get the parameter (file name)
638
    local cmdidx=1
639
    while [[ ! "${!cmdidx}" = "--log"* ]] && [[ ! "${!cmdidx}" = "--LOG"* ]]; do
640
      cmdidx=$[cmdidx + 1]
641
    done
642
    local cmd="${!cmdidx}"
643
    local logfile=""
644
    if [[ "$cmd" = "--log="* ]] || [[ "$cmd" = "--LOG="* ]]; then
645
      logfile=${cmd#*=}
646
    else
647
      local filenameidx=$((cmdidx + 1))
648
      logfile="${!filenameidx}"
649
    fi
650
    # optionally force silent appending
651
    if [[ "$cmd" = "--LOG"* ]]; then
652
      setLogFile --option=a --quiet "$logfile" LOG_FILE
653
    else
654
      setLogFile "$logfile" LOG_FILE
655
      printf "\n"
656
    fi
657
  fi
658

  
659
  # log script name
660
  printLog "this is $(realpath ${BASH_SOURCE[0]})\n"
661

  
662
  # if --help or -h was specified, print the help text and exit
663
  if [[ $@ == *"--help"* || $@ == *"-h"* ]]; then
664
    printHelp
665
    printf "\n"
666
    quitScript
667
  fi
668

  
669
  # detect installed versions and inform user
670
  local installedversions=()
671
  local currentversion=""
672
  detectInstalledVersions installedversions currentversion
673
  case "${#installedversions[@]}" in
674
    0)
675
      printInfo "no installation has been detected\n";;
676
    1)
677
      printInfo "1 installation has been detected:\n";;
678
    *)
679
      printInfo "${#installedversions[@]} installations have been detected:\n";;
680
  esac
681
  for (( idx=0; idx<${#installedversions[@]}; ++idx )); do
682
    if [ ${installedversions[$idx]} = "$currentversion" ]; then
683
      printInfo "  * ${installedversions[$idx]}\n"
684
    else
685
      printInfo "    ${installedversions[$idx]}\n"
686
    fi
687
  done
688
  printf "\n"
689

  
690
  # parse arguments
691
  local otherargs=()
692
  while [ $# -gt 0 ]; do
693
    if ( parseIsOption $1 ); then
694
      case "$1" in
695
        -h|--help) # already handled; ignore
696
          shift 1;;
697
        -i|--init)
698
          if [ -z "$currentversion" ]; then
699
            installNewVersion
700
          else
701
            installNewVersion --install=$(realpath $(dirname "$currentversion")/../../) --link=$(realpath $(dirname "$currentversion")/../../)
702
          fi
703
          printf "\n"; shift 1;;
704
        -c|--change)
705
          changeDefaultVersion installedversions[@] $(realpath $(dirname "$currentversion")/../../); printf "\n"; shift 1;;
706
        -q|--quit)
707
          quitScript; shift 1;;
708
        --log=*|--LOG=*) # already handled; ignore
709
          shift 1;;
710
        --log|--LOG) # already handled; ignore
711
          shift 2;;
712
        --noinfo) # already handled; ignore
713
          shift 1;;
714
        *)
715
          printError "invalid option: $1\n"; shift 1;;
716
      esac
717
    else
718
      otherargs+=("$1")
719
      shift 1
720
    fi
721
  done
722

  
723
  # interactive menu
724
  while ( true ); do
725
    # main menu info prompt and selection
726
    printInfo "GCC setup main menu\n"
727
    printf "Please select one of the following actions:\n"
728
    printf "  [I] - install another version\n"
729
    printf "  [C] - change default version\n"
730
    printf "  [Q] - quit this setup\n"
731
    local userinput=""
732
    readUserInput "IiCcQq" userinput
733
    printf "\n"
734

  
735
    # evaluate user selection
736
    case "$userinput" in
737
      I|i)
738
        if [ -z "$currentversion" ]; then
739
          installNewVersion
740
        else
741
          installNewVersion --install=$(realpath $(dirname "$currentversion")/../../) --link=$(realpath $(dirname "$currentversion")/../../)
742
        fi
743
        printf "\n";;
744
      C|c)
745
        changeDefaultVersion installedversions[@] $(realpath $(dirname "$currentversion")/../../); printf "\n";;
746
      Q|q)
747
        quitScript;;
748
      *) # sanity check (exit with error)
749
        printError "unexpected argument: $userinput\n";;
750
    esac
751
  done
752

  
753
  exit 0
754
}
755

  
756
################################################################################
757
# SCRIPT ENTRY POINT                                                           #
758
################################################################################
759

  
760
main "$@"
compiler/compilersetup.sh
1
################################################################################
2
# AMiRo-BLT is an bootloader and toolchain designed for the Autonomous Mini    #
3
# Robot (AMiRo) platform.                                                      #
4
# Copyright (C) 2016..2017  Thomas Schöpping et al.                            #
5
#                                                                              #
6
# This program is free software: you can redistribute it and/or modify         #
7
# it under the terms of the GNU General Public License as published by         #
8
# the Free Software Foundation, either version 3 of the License, or            #
9
# (at your option) any later version.                                          #
10
#                                                                              #
11
# This program is distributed in the hope that it will be useful,              #
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of               #
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                #
14
# GNU General Public License for more details.                                 #
15
#                                                                              #
16
# You should have received a copy of the GNU General Public License            #
17
# along with this program.  If not, see <http://www.gnu.org/licenses/>.        #
18
#                                                                              #
19
# This research/work was supported by the Cluster of Excellence Cognitive      #
20
# Interaction Technology 'CITEC' (EXC 277) at Bielefeld University, which is   #
21
# funded by the German Research Foundation (DFG).                              #
22
################################################################################
23

  
24
#!/bin/bash
25

  
26
################################################################################
27
# GENERIC FUNCTIONS                                                            #
28
################################################################################
29

  
30
### print an error message #####################################################
31
# Prints a error <message> to standard output.
32
#If variable 'LOG_FILE' is specified, the message is also appended to the given file.
33
#
34
# usage:      printError <message>
35
# arguments:  <message>
36
#                 Message string to print.
37
# return:     n/a
38
#
39
function printError {
40
  local string="ERROR:   $1"
41
  # if a log file is specified
42
  if [ -n "$LOG_FILE" ]; then
43
    printf "[$(date '+%Y-%m-%d %H:%M:%S')] $string" >> $LOG_FILE
44
  fi
45
  printf "$(tput setaf 1)>>> $string$(tput sgr 0)" 1>&2
46
}
47

  
48
### print a warning message ####################################################
49
# Prints a warning <message> to standard output.
50
#If variable 'LOG_FILE' is specified, the message is also appended to the given file.
51
#
52
# usage:      printMessage <message>
53
# arguments:  <message>
54
#                 Message string to print.
55
# return:     n/a
56
#
57
function printWarning {
58
  local string="WARNING: $1"
59
  # if a log file is specified
60
  if [ -n "$LOG_FILE" ]; then
61
    printf "[$(date '+%Y-%m-%d %H:%M:%S')] $string" >> $LOG_FILE
62
  fi
63
  printf "$(tput setaf 3)>>> $string$(tput sgr 0)"
64
}
65

  
66
### print an information message ###############################################
67
# Prints an information <message> to standard output.
68
#If variable 'LOG_FILE' is specified, the message is also appended to the given file.
69
#
70
# usage:      printInfo <message>
71
# arguments:  <message>
72
#                 Message string to print.
73
# return:     n/a
74
#
75
function printInfo {
76
  local string="INFO:    $1"
77
  # if a log file is specified
78
  if [ -n "$LOG_FILE" ]; then
79
    printf "[$(date '+%Y-%m-%d %H:%M:%S')] $string" >> $LOG_FILE
80
  fi
81
  printf "$(tput setaf 2)>>> $string$(tput sgr 0)"
82
}
83

  
84
### print a message to file ####################################################
85
# Appends a <message> to a log file, specified by the variable 'LOG_FILE'.
86
#
87
# usage       printLog <message>
88
# arguments:  <message>
89
#                 Message string to print.
90
# return:     n/a
91
#
92
function printLog {
93
  local string="LOG:     $1"
94
  # if a log file is specified
95
  if [ -n "$LOG_FILE" ]; then
96
    printf "[$(date '+%Y-%m-%d %H:%M:%S')] $string" >> $LOG_FILE
97
  fi
98
}
99

  
100
### exit the script normally ###################################################
101
# Prints a delimiter and exits the script normally (returns 0).
102
#
103
# usage:      quitScript
104
# arguments:  n/a
105
# return:     0
106
#                 No error or warning occurred.
107
#
108
function quitScript {
109
  printLog "exiting $(realpath ${BASH_SOURCE[0]})\n"
110
  printf "######################################################################\n"
111
  exit 0
112
}
113

  
114
### read a user input ##########################################################
115
# Reads a single character user input from a set up <options> and stores it in
116
# a given <return> variable.
117
#
118
# usage:      readUserInput <options> <return>
119
# arguments:  <options>
120
#                 String definiing the set of valid characters.
121
#                 If the string is empty, the user can input any character.
122
#             <return>
123
#                 Variable to store the selected character to.
124
# return:     n/a
125
#
126
function readUserInput {
127
  local input=""
128
  # read user input
129
  while [ -z $input ] || ( [ -n "$1" ] && [[ ! $input =~ ^[$1]$ ]] ); do
130
    read -p "your selection: " -n 1 -e input
131
    if [ -z $input ] || ( [ -n "$1" ] && [[ ! $input =~ ^[$1]$ ]] ); then
132
      printWarning "[$input] is no valid action\n"
133
    fi
134
  done
135
  printLog "[$input] has been selected\n"
136
  eval $2="$input"
137
}
138

  
139
### check whether argument is an option ########################################
140
# Checks a <string> whether it is an option.
141
# Options are defined to either start with '--' followed by any string, or
142
# to start with a single '-' followed by a single character, or
143
# to start with a single '-' followed by a single character, a '=' and any string.
144
# Examples: '--option', '--option=arg', '-o', '-o=arg', '--'
145
#
146
# usage:      parseIsOption <string>
147
# arguments:  <string>
148
#                 A string to check whether it is an option.
149
# return:     0
150
#                 <string> is an option.
151
#             -1
152
#                 <string> is not an option.
153
#
154
function parseIsOption {
155
  if [[ "$1" =~ ^-(.$|.=.*) ]] || [[ "$1" =~ ^--.* ]]; then
156
    return 0
157
  else
158
    return -1
159
  fi
160
}
161

  
162
### set the log file ###########################################################
163
# Sets a specified <infile> as log file and checks whether it already exists.
164
# If so, the log may either be appended to the file, its content can be cleared,
165
# or no log is generated at all.
166
# The resulting path is stored in <outvar>.
167
#
168
# usage:      setLogFile [--option=<option>] [--quiet] <infile> <outvar>
169
# arguments:  --option=<option>
170
#                 Select what to do if <file> already exists.
171
#                 Possible values are 'a', 'r' and 'n'.
172
#                 - a: append
173
#                 - r: delete and restart
174
#                 - n: no log
175
#                 If no option is secified but <file> exists, an interactive selection is provided.
176
#             --quiet
177
#                 Suppress all messages.
178
#             <infile>
179
#                 Path of the wanted log file.
180
#             <outvar>
181
#                 Variable to store the path of the log file to.
182
# return:     0
183
#                 No error or warning occurred.
184
#             -1
185
#                 Error: invalid input
186
#
187
function setLogFile {
188
  local filepath=""
189
  local option=""
190
  local quiet=false
191

  
192
  # parse arguments
193
  local otherargs=()
194
  while [ $# -gt 0 ]; do
195
    if ( parseIsOption $1 ); then
196
      case "$1" in
197
        -o=*|--option=*)
198
          option=${1#*=}; shift 1;;
199
        -o*|--option*)
200
          option="$2"; shift 2;;
201
        -q|--quiet)
202
          quiet=true; shift 1;;
203
        *)
204
          printError "invalid option: $1\n"; shift 1;;
205
      esac
206
    else
207
      otherargs+=("$1")
208
      shift 1
209
    fi
210
  done
211
  filepath=$(realpath ${otherargs[0]})
212

  
213
  # if file already exists
214
  if [ -e $filepath ]; then
215
    # if no option was specified, ask what to do
216
    if [ -z "$option" ]; then
217
      printWarning "log file $filepath already esists\n"
218
      local userinput=""
219
      printf "Select what to do:\n"
220
      printf "  [A] - append log\n"
221
      printf "  [R] - restart log (delete existing file)\n"
222
      printf "  [N] - no log\n"
223
      readUserInput "AaRrNn" userinput
224
      option=${userinput,,}
225
    fi
226
    # evaluate option
227
    case "$option" in
228
      a)
229
        if [ $quiet = false ]; then
230
          printInfo "appending log to $filepath\n"
231
        fi
232
        printf "\n" >> $filepath
233
        printf "######################################################################\n" >> $filepath
234
        printf "\n" >> $filepath
235
        ;;
236
      r)
237
        echo -n "" > $filepath
238
        if [ $quiet = false ]; then
239
          printInfo "content of $filepath wiped\n"
240
        fi
241
        ;;
242
      n)
243
        if [ $quiet = false ]; then
244
          printInfo "no log file will be generated\n"
245
        fi
246
        filepath=""
247
        ;;
248
      *) # sanity check (return error)
249
        printError "unexpected argument: $option\n"; return -1;;
250
    esac
251
  else
252
    if [ $quiet = false ]; then
253
      printInfo "log file set to $filepath\n"
254
    fi
255
  fi
256

  
257
  eval ${otherargs[1]}="$filepath"
258

  
259
  return 0
260
}
261

  
262
################################################################################
263
# SPECIFIC FUNCTIONS                                                           #
264
################################################################################
265

  
266
### print welcome text #########################################################
267
# Prints a welcome message to standard out.
268
#
269
# usage:      printWelcomeText
270
# arguments:  n/a
271
# return:     n/a
272
#
273
function printWelcomeText {
274
  printf "######################################################################\n"
275
  printf "#                                                                    #\n"
276
  printf "#              Welcome to the AMiRo-BLT compiler setup!              #\n"
277
  printf "#                                                                    #\n"
278
  printf "######################################################################\n"
279
  printf "#                                                                    #\n"
280
  printf "# Copyright (c) 2016..2017  Thomas Schöpping                         #\n"
281
  printf "#                                                                    #\n"
282
  printf "# This is free software; see the source for copying conditions.      #\n"
283
  printf "# There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR  #\n"
284
  printf "# A PARTICULAR PURPOSE. The development of this software was         #\n"
285
  printf "# supported by the Excellence Cluster EXC 227 Cognitive Interaction  #\n"
286
  printf "# Technology. The Excellence Cluster EXC 227 is a grant of the       #\n"
287
  printf "# Deutsche Forschungsgemeinschaft (DFG) in the context of the German #\n"
288
  printf "# Excellence Initiative.                                             #\n"
289
  printf "#                                                                    #\n"
290
  printf "######################################################################\n"
291
}
292

  
293
### print help #################################################################
294
# Prints a help text to standard out.
295
#
296
# usage:      printHelp
297
# arguments:  n/a
298
# return:     n/a
299
#
300
function printHelp {
301
  printInfo "printing help text\n"
302
  printf "usage:    $(basename ${BASH_SOURCE[0]}) [-h|--help] [--GCC] [-q|--quit] [--log=<file>]\n"
303
  printf "\n"
304
  printf "options:  -h, --help\n"
305
  printf "              Print this help text.\n"
306
  printf "          --GCC\n"
307
  printf "              Enter GCC setup.\n"
308
  printf "          -q, --quit\n"
309
  printf "              Quit the script.\n"
310
  printf "          --log=<file>\n"
311
  printf "              Specify a log file.\n"
312
}
313

  
314
### enter GCC setup ############################################################
315
# Enter the arm-none-eabi-gcc setup.
316
#
317
# usage:      gccSetup
318
# arguments:  n/a
319
# return:     n/a
320
function gccSetup {
321
  printInfo "entering GCC setup...\n"
322
  printf "\n"
323
  if [ -z "$LOG_FILE" ]; then
324
    $(realpath $(dirname ${BASH_SOURCE[0]}))/GCC/gccsetup.sh --noinfo
325
  else
326
    $(realpath $(dirname ${BASH_SOURCE[0]}))/GCC/gccsetup.sh --LOG="$LOG_FILE" --noinfo
327
  fi
328
}
329

  
330
### main function of this script ###############################################
331
# The IDE setup lets the user select an IDE of choice.
332
# As of now, only QtCreator is supported.
333
#
334
# usage:      see function printHelp
335
# arguments:  see function printHelp
336
# return:     0
337
#                 No error or warning occurred.
338
#
339
function main {
340
  # print welcome/info text if not suppressed
341
  if [[ $@ != *"--noinfo"* ]]; then
342
    printWelcomeText
343
  else
344
    printf "######################################################################\n"
345
  fi
346
  printf "\n"
347

  
348
  # set log file if specified
349
  if [[ $@ == *"--log"* ]] || [[ $@ == *"--LOG"* ]]; then
350
    # get the parameter (file name)
351
    local cmdidx=1
352
    while [[ ! "${!cmdidx}" = "--log"* ]] && [[ ! "${!cmdidx}" = "--LOG"* ]]; do
353
      cmdidx=$[cmdidx + 1]
354
    done
355
    local cmd="${!cmdidx}"
356
    local logfile=""
357
    if [[ "$cmd" = "--log="* ]] || [[ "$cmd" = "--LOG="* ]]; then
358
      logfile=${cmd#*=}
359
    else
360
      local filenameidx=$((cmdidx + 1))
361
      logfile="${!filenameidx}"
362
    fi
363
    # optionally force silent appending
364
    if [[ "$cmd" = "--LOG"* ]]; then
365
      setLogFile --option=a --quiet "$logfile" LOG_FILE
366
    else
367
      setLogFile "$logfile" LOG_FILE
368
      printf "\n"
369
    fi
370
  fi
371

  
372
  # log script name
373
  printLog "this is $(realpath ${BASH_SOURCE[0]})\n"
374

  
375
  # if --help or -h was specified, print the help text and exit
376
  if [[ $@ == *"--help"* || $@ == *"-h"* ]]; then
377
    printHelp
378
    printf "\n"
379
    quitScript
380
  fi
381

  
382
  # parse arguments
383
  local otherargs=()
384
  while [ $# -gt 0 ]; do
385
    if ( parseIsOption $1 ); then
386
      case "$1" in
387
        -h|--help) # already handled; ignore
388
          shift 1;;
389
        --GCC)
390
          gccSetup; printf "\n"; shift 1;;
391
        -q|--quit)
392
          quitScript; printf "\n"; shift 1;;
393
        --log=*|--LOG=*) # already handled; ignore
394
          shift 1;;
395
        --log|--LOG) # already handled; ignore
396
          shift 2;;
397
        --noinfo) # already handled; ignore
398
          shift 1;;
399
        *)
400
          printError "invalid option: $1\n"; shift 1;;
401
      esac
402
    else
403
      otherargs+=("$1")
404
      shift 1
405
    fi
406
  done
407

  
408
  # interactive menu
409
  while ( true ); do
410
    # main menu info prompt and selection
411
    printInfo "AMiRo-BLT compiler setup main menu\n"
412
    printf "Please select one of the following actions:\n"
413
    printf "  [G] - enter GCC setup\n"
414
    printf "  [Q] - quit this setup\n"
415
    local userinput=""
416
    readUserInput "GgQq" userinput
417
    printf "\n"
418

  
419
    # evaluate user selection
420
    case "$userinput" in
421
      G|g)
422
        gccSetup; printf "\n";;
423
      Q|q)
424
        quitScript;;
425
      *) # sanity check (exit with error)
426
        printError "unexpected argument: $userinput\n"; printf "\n";;
427
    esac
428
  done
429

  
430
  exit 0
431
}
432

  
433
################################################################################
434
# SCRIPT ENTRY POINT                                                           #
435
################################################################################
436

  
437
main "$@"
ide/QtCreator/QtCreatorSetup.sh
27 27
# GENERIC FUNCTIONS                                                            #
28 28
################################################################################
29 29

  
30
### print an error
31
# arguments:
32
#   - error string [required]
33
# return: n/a
30
### print an error message #####################################################
31
# Prints a error <message> to standard output.
32
#If variable 'LOG_FILE' is specified, the message is also appended to the given file.
33
#
34
# usage:      printError <message>
35
# arguments:  <message>
36
#                 Message string to print.
37
# return:     n/a
38
#
34 39
function printError {
35 40
  local string="ERROR:   $1"
36

  
37 41
  # if a log file is specified
38
  if [ ! -z $LOG_FILE ]; then
42
  if [ -n "$LOG_FILE" ]; then
39 43
    printf "[$(date '+%Y-%m-%d %H:%M:%S')] $string" >> $LOG_FILE
40 44
  fi
41 45
  printf "$(tput setaf 1)>>> $string$(tput sgr 0)" 1>&2
42 46
}
43 47

  
44
### print a warning
45
# arguments:
46
#   - warning string [required]
47
# return: n/a
48
### print a warning message ####################################################
49
# Prints a warning <message> to standard output.
50
#If variable 'LOG_FILE' is specified, the message is also appended to the given file.
51
#
52
# usage:      printMessage <message>
53
# arguments:  <message>
54
#                 Message string to print.
55
# return:     n/a
56
#
48 57
function printWarning {
49 58
  local string="WARNING: $1"
50

  
51 59
  # if a log file is specified
52
  if [ ! -z $LOG_FILE ]; then
60
  if [ -n "$LOG_FILE" ]; then
53 61
    printf "[$(date '+%Y-%m-%d %H:%M:%S')] $string" >> $LOG_FILE
54 62
  fi
55
  printf "$(tput setaf 3)>>> $string$(tput sgr 0)" 1>&2
63
  printf "$(tput setaf 3)>>> $string$(tput sgr 0)"
56 64
}
57 65

  
58
### print an information text
59
# arguments:
60
#   - information string [required]
61
# return: n/a
66
### print an information message ###############################################
67
# Prints an information <message> to standard output.
68
#If variable 'LOG_FILE' is specified, the message is also appended to the given file.
69
#
70
# usage:      printInfo <message>
71
# arguments:  <message>
72
#                 Message string to print.
73
# return:     n/a
74
#
62 75
function printInfo {
63 76
  local string="INFO:    $1"
64

  
65 77
  # if a log file is specified
66
  if [ ! -z $LOG_FILE ]; then
78
  if [ -n "$LOG_FILE" ]; then
67 79
    printf "[$(date '+%Y-%m-%d %H:%M:%S')] $string" >> $LOG_FILE
68 80
  fi
69
  printf "$(tput setaf 2)>>> $string$(tput sgr 0)" 1>&2
81
  printf "$(tput setaf 2)>>> $string$(tput sgr 0)"
70 82
}
71 83

  
72
### print a message to the log file
73
# arguments:
74
#   - information string [required]
75
# return: n/a
84
### print a message to file ####################################################
85
# Appends a <message> to a log file, specified by the variable 'LOG_FILE'.
86
#
87
# usage       printLog <message>
88
# arguments:  <message>
89
#                 Message string to print.
90
# return:     n/a
91
#
76 92
function printLog {
77 93
  local string="LOG:     $1"
78

  
79 94
  # if a log file is specified
80
  if [ ! -z $LOG_FILE ]; then
95
  if [ -n "$LOG_FILE" ]; then
81 96
    printf "[$(date '+%Y-%m-%d %H:%M:%S')] $string" >> $LOG_FILE
82 97
  fi
83 98
}
84 99

  
85
### exit the script normally
86
# arguments: n/a
87
# return: 0 (success)
100
### exit the script normally ###################################################
101
# Prints a delimiter and exits the script normally (returns 0).
102
#
103
# usage:      quitScript
104
# arguments:  n/a
105
# return:     0
106
#                 No error or warning occurred.
107
#
88 108
function quitScript {
89
  printInfo "exiting $(realpath ${BASH_SOURCE[0]})\n"
90
  printf "\n"
109
  printLog "exiting $(realpath ${BASH_SOURCE[0]})\n"
91 110
  printf "######################################################################\n"
92

  
93 111
  exit 0
94 112
}
95 113

  
96
### read a user input
97
# arguments:
98
#   --numchars, -n  maximum number of characters to read
99
#   --options, -o   possible chacters to select (only applies if numchars=1)
100
#   --out, -e       output variable to store the user input to
101
# return: error code
102
#   -  0: no error
103
#   - -1: error: invalid arguments
114
### read a user input ##########################################################
115
# Reads a single character user input from a set up <options> and stores it in
116
# a given <return> variable.
117
#
118
# usage:      readUserInput <options> <return>
119
# arguments:  <options>
120
#                 String definiing the set of valid characters.
121
#                 If the string is empty, the user can input any character.
122
#             <return>
123
#                 Variable to store the selected character to.
124
# return:     n/a
125
#
104 126
function readUserInput {
105
  # parse arguments
106
  local arguments=$(getopt -l num-chars:,options:,out: -o n:o:e: -- "$@")
107
  if [ $? != 0 ]; then
108
    printError "could not interprete arguments."
109
    return -1
110
  fi
111
  eval set -- "$arguments"
112

  
113
  # evaluate arguments
114
  local numchars=0
115
  local options=""
116
  local outvar=""
117
  while [ true ]; do
118
    case "$1" in
119
      --num-chars|-n)
120
        numchars=$2; shift 2
121
        ;;
122
      --options|-o)
123
        options="$2"; shift 2
124
        ;;
125
      --out|-e)
126
        outvar=$2; shift 2
127
        ;;
128
      --) # end of options reached
129
        shift; break
130
        ;;
131
      *) # sanity check (return error)
132
        printError "unexpected argument: $1\n"; return -1
133
        ;;
134
    esac
135
  done
136

  
127
  local input=""
137 128
  # read user input
138
  local _userinput=""
139
  while [ -z $_userinput ] || ( [ $numchars == 1 ] && [ ! -z "$options" ] && [[ ! $_userinput =~ ^["$options"]$ ]] ); do
140
    if [ $numchars == 0 ]; then
141
      read -p "your selection: " -e _userinput
142
    else
143
      read -p "your selection: " -n $numchars -e _userinput
144
    fi
145
    if [ -z $_userinput ] || ( [ $numchars == 1 ] && [ ! -z "$options" ] && [[ ! $_userinput =~ ^["$options"]$ ]] ); then
146
      printWarning "[$_userinput] is no valid action\n"
129
  while [ -z $input ] || ( [ -n "$1" ] && [[ ! $input =~ ^[$1]$ ]] ); do
130
    read -p "your selection: " -n 1 -e input
131
    if [ -z $input ] || ( [ -n "$1" ] && [[ ! $input =~ ^[$1]$ ]] ); then
132
      printWarning "[$input] is no valid action\n"
147 133
    fi
148 134
  done
149
  printLog "[$_userinput] has been selected\n"
150
  if [ ! -z "$outvar" ]; then
151
    eval $outvar="$_userinput"
152
  fi
153

  
154
  return 0
135
  printLog "[$input] has been selected\n"
136
  eval $2="$input"
155 137
}
156 138

  
157
### set the log file
158
# arguments:
159
#   --file, -f    name of file [required]
160
#   --option, -o  option if file already exists [optional]
161
#                 a: append
162
#                 r: delete and restart
163
#                 n: disable log
164
#                 A: silent append (no message in the log file)
165
# return: error code
166
#   -  0: no error
167
#   -  1: warning: file already exists
168
#   -  2: warning: no file specified
169
#   - -1: error: invalid arguments
170
function setLogFile {
171
  # parse arguments
172
  local arguments=$(getopt -l file:,option: -o f:o: -- "$@")
173
  if [ $? != 0 ]; then
174
    printError "could not interprete arguments."
139
### check whether argument is an option ########################################
140
# Checks a <string> whether it is an option.
141
# Options are defined to either start with '--' followed by any string, or
142
# to start with a single '-' followed by a single character, or
143
# to start with a single '-' followed by a single character, a '=' and any string.
144
# Examples: '--option', '--option=arg', '-o', '-o=arg', '--'
145
#
146
# usage:      parseIsOption <string>
147
# arguments:  <string>
148
#                 A string to check whether it is an option.
149
# return:     0
150
#                 <string> is an option.
151
#             -1
152
#                 <string> is not an option.
153
#
154
function parseIsOption {
155
  if [[ "$1" =~ ^-(.$|.=.*) ]] || [[ "$1" =~ ^--.* ]]; then
156
    return 0
157
  else
175 158
    return -1
176 159
  fi
177
  eval set -- "$arguments"
160
}
178 161

  
179
  # evaluate arguments
180
  local fname=""
162
### set the log file ###########################################################
163
# Sets a specified <infile> as log file and checks whether it already exists.
164
# If so, the log may either be appended to the file, its content can be cleared,
165
# or no log is generated at all.
166
# The resulting path is stored in <outvar>.
167
#
168
# usage:      setLogFile [--option=<option>] [--quiet] <infile> <outvar>
169
# arguments:  --option=<option>
170
#                 Select what to do if <file> already exists.
171
#                 Possible values are 'a', 'r' and 'n'.
172
#                 - a: append
173
#                 - r: delete and restart
174
#                 - n: no log
175
#                 If no option is secified but <file> exists, an interactive selection is provided.
176
#             --quiet
177
#                 Suppress all messages.
178
#             <infile>
179
#                 Path of the wanted log file.
180
#             <outvar>
181
#                 Variable to store the path of the log file to.
182
# return:     0
183
#                 No error or warning occurred.
184
#             -1
185
#                 Error: invalid input
186
#
187
function setLogFile {
188
  local filepath=""
181 189
  local option=""
182
  while [ true ]; do
183
    case "$1" in
184
      --file|f)
185
        if [ ! -z $2 ]; then
186
          fname="$(dirname $2)/$(basename $2)"
187
        else
188
          fname=""
189
        fi
190
        shift 2
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff