Statistics
| Branch: | Tag: | Revision:

amiro-os / bootloader / bootloadersetup.sh @ 9e75cdad

History | View | Annotate | Download (20.25 KB)

1
################################################################################
2
# AMiRo-OS is an operating system designed for the Autonomous Mini Robot       #
3
# (AMiRo) platform.                                                            #
4
# Copyright (C) 2016..2018  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
  printInfo "exiting $(realpath ${BASH_SOURCE[0]})\n"
110
  printf "\n"
111
  printf "######################################################################\n"
112
  exit 0
113
}
114

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

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

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

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

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

    
261
  eval ${otherargs[1]}="$filepath"
262

    
263
  return 0
264
}
265

    
266
################################################################################
267
# SPECIFIC FUNCTIONS                                                           #
268
################################################################################
269

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

    
297
### print help #################################################################
298
# Prints a help text to standard out.
299
#
300
# usage:      printHelp
301
# arguments:  n/a
302
# return:     n/a
303
#
304
function printHelp {
305
  printInfo "printing help text\n"
306
  printf "usage:    $(basename ${BASH_SOURCE[0]}) [-h|--help] [-i|--init] [-s|--setup] [-w|--wipe] [-q|--quit] [--log=<file>]\n"
307
  printf "options:  -h, --help\n"
308
  printf "              Print this help text.\n"
309
  printf "          -i, --init\n"
310
  printf "              Initialize the AMiRo-BLT submodule.\n"
311
  printf "          -s, --setup\n"
312
  printf "              Enter AMiRo-BLT setup.\n"
313
  printf "          -w, --wipe\n"
314
  printf "              Wipe the entire AMiRo-BLT submodule.\n"
315
  printf "          -q, --quit\n"
316
  printf "              Quit the script.\n"
317
  printf "          --log=<file> \n"
318
  printf "              Specify a log file.\n"
319
}
320

    
321
### initialize AMiRo-BLT submodule #############################################
322
# Initialize the AMiRo-BLT submodule.
323
#
324
# usage:      initAmiroBlt
325
# arguments:  n/a
326
# return:     0
327
#                 No error or warning occurred.
328
#             1
329
#                 Warning: Arborted by user.
330
#             -1
331
#                 Error: Unexpected user input.
332
#
333
function initAmiroBlt {
334
  printInfo "initializing AMiRo-BLT submodule...\n"
335
  local userdir=$(pwd)
336
  local bootloaderdir=$(dirname $(realpath ${BASH_SOURCE[0]}))
337
  local amirobltdir=${bootloaderdir}/AMiRo-BLT
338

    
339
  # if the AMiRo-BLT folder is not empty
340
  if [ ! -z "$(ls -A $amirobltdir)" ]; then
341
    printWarning "$(realpath $amirobltdir) is not empty. Delete and reinitialize? [y/n]\n"
342
    local userinput=""
343
    readUserInput "YyNn" userinput
344
    case $userinput in
345
      Y|y)
346
        wipeAmiroBlt
347
        ;;
348
      N|n)
349
        printWarning "AMiRo-BLT initialization aborted by user\n"
350
        return 1
351
        ;;
352
      *) # sanity check (return error)
353
        printError "unexpected input: $userinput\n"; return -1;;
354
    esac
355
  fi
356

    
357
  # initialize submodule to default branch
358
  cd $bootloaderdir
359
  git submodule update --init $amirobltdir 2>&1 | tee -a $LOG_FILE
360
  while [ ${PIPESTATUS[0]} -ne 0 ]; do
361
    printWarning "initialitaion failed. Retry? [y/n]\n"
362
    local userinput=""
363
    readUserInput "YyNn" userinput
364
    case "$userinput" in
365
      Y|y)
366
        git submodule update --init $amirobltdir 2>&1 | tee -a $LOG_FILE;;
367
      N|n)
368
        printWarning "AMiRo-BLT initialization aborted by user\n"
369
        cd $userdir
370
        return 1
371
        ;;
372
      *) # sanity check (return error)
373
        printError "unexpected input: $userinput\n"; return -1;;
374
    esac
375
  done
376
  cd $userdir
377

    
378
  return 0
379
}
380

    
381
### enter AMiRo-BLT setup ######################################################
382
# Enter AMiRo-BLT submodule setup.
383
#
384
# usage:      amiroBltSetup
385
# arguments:  n/a
386
# return:     0
387
#                 No error or warning occurred.
388
#             -1
389
#                 Error: AMiRo-BLT submodule not initialized yet.
390
#
391
function amiroBltSetup {
392
  local amirobltdir=$(dirname $(realpath ${BASH_SOURCE[0]}))/AMiRo-BLT
393

    
394
  # check if AMiRo-BLT submodule is initialized
395
  if [ -z "$(ls -A $amirobltdir)" ]; then
396
    printError "$amirobltdir is empty. Please initialize first.\n"
397
    return -1
398
  else
399
    printInfo "entering AMiRo-BLT setup\n"
400
    printf "\n"
401
    if [ -z "$LOG_FILE" ]; then
402
      ${amirobltdir}/setup.sh --noinfo
403
    else
404
      ${amirobltdir}/setup.sh --LOG="$LOG_FILE" --noinfo
405
    fi
406
    return 0
407
  fi
408
}
409

    
410
### reset AMiRo-BLT submodule and wipe directory ###############################
411
# Resets the AMiRo-BLT Git submodule and wipes the directory.
412
#
413
# usage:      wipeAmiroBlt
414
# arguments:  n/a
415
# return:     n/a
416
function wipeAmiroBlt {
417
  printInfo "reset and wipe Git submodule $amirobltdir\n"
418
  local userdir=$(pwd)
419
  local bootloaderdir=$(dirname $(realpath ${BASH_SOURCE[0]}))
420
  local amirobltdir=${bootloaderdir}/AMiRo-BLT
421

    
422
  # if the AMiRo-BLT folder is empty
423
  if [ -z "$(ls -A $amirobltdir)" ]; then
424
    printWarning "$amirobltdir is already empty\n"
425
    return 1
426
  else
427
    # get some information from Git
428
    cd $bootloaderdir
429
    local git_basehash=($(git ls-tree -d HEAD $amirobltdir)); git_basehash=${git_basehash[2]}
430
    cd $amirobltdir
431
    local git_branch_current=$(git rev-parse --abbrev-ref HEAD)
432
    local git_difftobase="$(git diff ${git_basehash}..HEAD)"
433
    local git_commits=$(git log --format=oneline ${git_basehash}..HEAD)
434
    local git_dirtyfiles=($(git ls-files -dmo --exclude-standard --exclude=/doc))
435
    cd $userdir
436
    local issues=0
437
    # if HEAD is ahead of submodule base commit
438
    if [ -n "$git_difftobase" ]; then
439
      issues=$((issues + 1))
440
      printWarning "HEAD is ahead of submodule base\n"
441
    fi
442
    # if there are untracked, modified, or deleted files
443
    if [ ${#git_dirtyfiles[@]} != 0 ]; then
444
      issues=$((issues + 1))
445
      printWarning "there are ${#git_dirtyfiles[@]} untracked, modified, or deleted files\n"
446
    fi
447
    if [ $issues -gt 0 ]; then
448
      local userinput=""
449
      printWarning "$issues issues detected. Do you want to continue? [y/n]\n"
450
      readUserInput "YyNn" userinput
451
      case "$userinput" in
452
        Y|y)
453
          ;;
454
        N|n)
455
          printfWarning "wiping AMiRo-BLT Git submodule aborted by user\n"
456
          return 2
457
          ;;
458
        *) # sanity check (return error)
459
          printError "unexpected input: $userinput\n"; return -1;;
460
      esac
461
    fi
462

    
463
    # checkout base commit and delete all local branches
464
    cd $bootloaderdir
465
    git submodule update --force --checkout $amirobltdir | tee -a $LOG_FILE
466
    cd $amirobltdir
467
    local git_branches=($(git for-each-ref --format="%(refname)"))
468
    for branch in $git_branches; do
469
      if [[ $branch = *"heads/"* ]]; then
470
        git branch -D ${branch##*/} | tee -a $LOG_FILE
471
      fi
472
    done
473
    cd $userdir
474

    
475
    # deinitialize AMiRo-BLT submodule and delete any remaining files
476
    cd $bootloaderdir
477
    git submodule deinit -f $amirobltdir 2>&1 | tee -a $LOG_FILE
478
    rm -rf $amirobltdir/*
479
    cd $userdir
480

    
481
    return 0
482
  fi
483
}
484

    
485
### main function of this script ###############################################
486
# Initializes or wipes the AMiRo-BLT Git submodule, and provides an entry point
487
# to its setup.
488
#
489
# usage:      see function printHelp
490
# arguments:  see function printHelp
491
# return:     0
492
#                 No error or warning occurred.
493
#
494
function main {
495
  # print welcome/info text if not suppressed
496
  if [[ $@ != *"--noinfo"* ]]; then
497
    printWelcomeText
498
  else
499
    printf "######################################################################\n"
500
  fi
501
  printf "\n"
502

    
503
  # if --help or -h was specified, print the help text and exit
504
  if [[ $@ == *"--help"* || $@ == *"-h"* ]]; then
505
    printHelp
506
    printf "\n"
507
    quitScript
508
  fi
509

    
510
  # set log file if specified
511
  if [[ $@ == *"--log"* ]] || [[ $@ == *"--LOG"* ]]; then
512
    # get the parameter (file name)
513
    local cmdidx=1
514
    while [[ ! "${!cmdidx}" = "--log"* ]] && [[ ! "${!cmdidx}" = "--LOG"* ]]; do
515
      cmdidx=$[cmdidx + 1]
516
    done
517
    local cmd="${!cmdidx}"
518
    local logfile=""
519
    if [[ "$cmd" = "--log="* ]] || [[ "$cmd" = "--LOG="* ]]; then
520
      logfile=${cmd#*=}
521
    else
522
      local filenameidx=$((cmdidx + 1))
523
      logfile="${!filenameidx}"
524
    fi
525
    # optionally force silent appending
526
    if [[ "$cmd" = "--LOG"* ]]; then
527
      setLogFile --option=c --quiet "$logfile" LOG_FILE
528
    else
529
      setLogFile "$logfile" LOG_FILE
530
      printf "\n"
531
    fi
532
  fi
533
  # log script name
534
  printLog "this is $(realpath ${BASH_SOURCE[0]})\n"
535

    
536
  # parse arguments
537
  local otherargs=()
538
  while [ $# -gt 0 ]; do
539
    if ( parseIsOption $1 ); then
540
      case "$1" in
541
        -h|--help) # already handled; ignore
542
          shift 1;;
543
        -i|--init)
544
           initAmiroBlt; printf "\n"; shift 1;;
545
        -s|--setup)
546
           amiroBltSetup; printf "\n"; shift 1;;
547
        -w|--wipe)
548
           wipeAmiroBlt; printf "\n"; shift 1;;
549
        -q|--quit)
550
          quitScript; shift 1;;
551
        --log=*|--LOG=*) # already handled; ignore
552
          shift 1;;
553
        --log|--LOG) # already handled; ignore
554
          shift 2;;
555
        --noinfo) # already handled; ignore
556
          shift 1;;
557
        *)
558
          printError "invalid option: $1\n"; shift 1;;
559
      esac
560
    else
561
      otherargs+=("$1")
562
      shift 1
563
    fi
564
  done
565

    
566
  # interactive menu
567
  while ( true ); do
568
    # main menu info prompt and selection
569
    printInfo "Bootloader setup main menu\n"
570
    printf "Please select one of the following actions:\n"
571
    printf "  [I] - initialize AMiRo-BLT submodule\n"
572
    printf "  [S] - enter AMiRo-BLT setup\n"
573
    printf "  [W] - wipe AMiRo-BLT submodule\n"
574
    printf "  [Q] - quit this setup\n"
575
    local userinput=""
576
    readUserInput "IiSsWwQq" userinput
577
    printf "\n"
578

    
579
    # evaluate user selection
580
    case "$userinput" in
581
      I|i)
582
        initAmiroBlt; printf "\n";;
583
      S|s)
584
        amiroBltSetup; printf "\n";;
585
      W|w)
586
        wipeAmiroBlt; printf "\n";;
587
      Q|q)
588
        quitScript;;
589
      *) # sanity check (exit with error)
590
        printError "unexpected argument: $userinput\n";;
591
    esac
592
  done
593

    
594
  exit 0
595
}
596

    
597
################################################################################
598
# SCRIPT ENTRY POINT                                                           #
599
################################################################################
600

    
601
main "$@"
602