Statistics
| Branch: | Tag: | Revision:

amiro-os / kernel / kernelsetup.sh @ 881a7932

History | View | Annotate | Download (28.528 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 ChibiOS 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] [-p|--patch] [-d|--documentation=<option>] [-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 ChibiOS submodule.\n"
311
  printf "          -p, --patch,\n"
312
  printf "              Apply patches to CHibiOS.\n"
313
  printf "          -d, --documentation <option>\n"
314
  printf "              Possible options are: 'g' and 'o' (can be combined).\n"
315
  printf "              - g: Generate HTML documentation of ChibiOS.\n"
316
  printf "              - o: Open HTML documentation of ChibiOS.\n"
317
  printf "          -w, --wipe\n"
318
  printf "              Wipe ChibiOS submodule.\n"
319
  printf "          -q, --quit\n"
320
  printf "              Quit the script.\n"
321
  printf "          --log=<file>\n"
322
  printf "              Specify a log file.\n"
323
}
324

    
325
### initialize ChibiOS submodule ###############################################
326
# Initializes the ChibiOS Git submodule.
327
#
328
# usage:      initChibiOS
329
# arguments:  n/a
330
# return:     0
331
#                 No error or warning occurred.
332
#             1
333
#                 Warning: Aborted by user.
334
#             -1
335
#                 Error: Unexpected user input.
336
#
337
function initChibiOS {
338
  printInfo "initializing ChibiOS submodule...\n"
339
  local userdir=$(pwd)
340
  local kerneldir=$(dirname $(realpath ${BASH_SOURCE[0]}))
341
  local chibiosdir=${kerneldir}/ChibiOS
342

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

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

    
382
  return 0
383
}
384

    
385
### patch ChibiOS ##############################################################
386
# Applies patches to ChibiOS submodule.
387
#
388
# usage:      patchChibiOS
389
# arguments:  n/a
390
# return:     0
391
#                 No error or warning occurred.
392
#             1
393
#                 Warning: ChibiOS not initialized yet.
394
#             2
395
#                 Warning: Setup aborted by user.
396
#             -1
397
#                 Error: Unexpected user input.
398
#
399
function patchChibiOS {
400
  printInfo "applying patches to ChibiOS\n"
401
  local userdir=$(pwd)
402
  local kerneldir=$(dirname $(realpath ${BASH_SOURCE[0]}))
403
  local chibiosdir=${kerneldir}/ChibiOS
404
  local git_branch_patched="AMiRo-OS"
405

    
406
  # if the ChibiOS folder is empty
407
  if [ -z "$(ls -A $chibiosdir)" ]; then
408
    printWarning "$chibiosdir is empty. Please initialize first.\n"
409
    return 1
410
  else 
411
    # get some information from Git
412
    cd $chibiosdir
413
    local git_branch_current=$(git rev-parse --abbrev-ref HEAD)
414
    local git_branches=$(git for-each-ref --format="%(refname)")
415
    local git_dirtyfiles=($(git ls-files -dmo --exclude-standard --exclude=/doc))
416
    cd $userdir
417

    
418
    local issues=0
419
    # if the current branch is already $git_branch_patched
420
    if [ "$git_branch_current" = "$git_branch_patched" ]; then
421
      issues=$((issues + 1))
422
      printWarning "current branch is already $git_branch_patched\n"
423
    fi
424
    # if the current branch is bot $git_branch_patched, but another branch $git_branch_patched already exists
425
    if [ "$git_branch_current" != "$git_branch_patched" ] && [[ "$git_branches" = *"$git_branch_patched"* ]]; then
426
      issues=$((issues + 1))
427
      printWarning "another branch $git_branch_patched already exists\n"
428
    fi
429
    # if there are untracked, modified, or deleted files
430
    if [ ${#git_dirtyfiles[@]} != 0 ]; then
431
      issues=$((issues + 1))
432
      printWarning "there are ${#git_dirtyfiles[@]} untracked, modified, or deleted files\n"
433
    fi
434
    if [ $issues -gt 0 ]; then
435
      local userinput=""
436
      printWarning "$issues issues detected. Do you want to continue? [y/n]\n"
437
      readUserInput "YyNn" userinput
438
      case "$userinput" in
439
        Y|y)
440
          ;;
441
        N|n)
442
          printfWarning "ChibiOS patching aborted by user\n"
443
          return 2
444
          ;;
445
        *) # sanity check (return error)
446
          printError "unexpected input: $userinput\n"; return -1;;
447
      esac
448
    fi
449

    
450
    # create a new branch and apply the patches
451
    local patches=${kerneldir}/patches/*.patch
452
    cd $chibiosdir
453
    git checkout -b "$git_branch_patched" 2>&1 | tee -a $LOG_FILE
454
    for patch in $patches; do
455
      cp $patch .
456
      patch=$(basename $patch)
457
      git apply --whitespace=nowarn --ignore-space-change --ignore-whitespace < $patch 2>&1 | tee -a $LOG_FILE
458
      rm $patch
459
#      # These lines are disabled for safety reasons:
460
#      #   Filed commits are detected as valid changes by the super-project.
461
#      #   This may lead to errorneous updates of the super-project, as to point to one of these commit hashes.
462
#      #   Since these commits are not pushed upstream, initialization of the super-project will therefore fail, because
463
#      #   the referenced hashed (after patching) do not exist in a clean copy of this sub-project.
464
#      git add $(git ls-files -dmo --exclude-standard --exclude=/doc) $(git diff --name-only) 2>&1 | tee -a $LOG_FILE
465
#      git commit --message="$patch applied" 2>&1 | tee -a $LOG_FILE
466
    done
467
    cd $userdir
468

    
469
    return 0
470
  fi
471
}
472

    
473
### ChibiOS dcoumentation setup ################################################
474
#
475
# usage:      documentation [<option>]
476
# arguments:  <option>
477
#                 Can be either 'g' or 'o' to generate or open HTML documentation respectively.
478
# return:     0
479
#                 No error or warning occurred.
480
#             1
481
#                 Warning: Kernel not nitialized yet.
482
#             2
483
#                 Warning: Setup aborted by user.
484
#             3
485
#                 Warning: Issues occurred.
486
#             -1
487
#                 Error: Unexpected user input.
488
#
489
function documentation {
490
  local userdir=$(pwd)
491
  local kerneldir=$(dirname $(realpath ${BASH_SOURCE[0]}))
492
  local chibiosdir=${kerneldir}/ChibiOS
493

    
494
  # if the ChibiOS folder is empty
495
  if [ -z "$(ls -A $chibiosdir)" ]; then
496
    printWarning "$chibiosdir is empty. Please initialize first.\n"
497
    return 1
498
  else
499
    local option="";
500
    # if no argument was specified, ask what to do
501
    if [ $# -eq 0 ]; then
502
      printInfo "ChibiOS documentation setup\n"
503
      printf "Please select one of the following actions:\n"
504
      printf "  [G] - generate HTML documentation\n"
505
      printf "  [O] - open HTML documentation\n"
506
      printf "  [A] - abort this setup\n"
507
      local userinput
508
      readUserInput "GgOoAa" userinput
509
      option=${userinput,,}
510
      if [ $option = "a" ]; then
511
        printInfo "ChibiOS documentation setup aborted by user\n"
512
        return 2
513
      fi
514
    else
515
      option="$1"
516
    fi
517

    
518
    local issues=0
519
    case "$option" in
520
      # generate HTML documentation
521
      g)
522
        # ChibiOS/HAL: check if required files exis
523
        if [ -f ${chibiosdir}/doc/hal/makehtml.sh ]; then
524
          printInfo "generating ChibiOS/HAL documentation...\n"
525
          cd ${chibiosdir}/doc/hal
526
          ${chibiosdir}/doc/hal/makehtml.sh 2>&1 | tee -a $LOG_FILE
527
          cd $userdir
528
          printInfo "access ChibiOS/HAL documentation via ${chibiosdir}doc/hal/html/index.html\n"
529
        else
530
          issues=$((issues + 1))
531
          printError "could not generate ChibiOS/HAL documentation\n"
532
        fi
533
        # ChibiOS/RT: check if required files exis
534
        if [ -f ${chibiosdir}/doc/rt/makehtml.sh ]; then
535
          printInfo "generating ChibiOS/RT documentation...\n"
536
          cd ${chibiosdir}/doc/rt
537
          ${chibiosdir}/doc/rt/makehtml.sh 2>&1 | tee -a $LOG_FILE
538
          cd $userdir
539
          printInfo "access ChibiOS/RT documentation via ${chibiosdir}doc/rt/html/index.html\n"
540
        else
541
          issues=$((issues + 1))
542
          printError "could not generate ChibiOS/RT documentation\n"
543
        fi
544
        # ChibiOS/NIL: check if required files exis
545
        if [ -f ${chibiosdir}/doc/nil/makehtml.sh ]; then
546
          printInfo "generating ChibiOS/NIL documentation...\n"
547
          cd ${chibiosdir}/doc/nil
548
          ${chibiosdir}/doc/nil/makehtml.sh 2>&1 | tee -a $LOG_FILE
549
          cd $userdir
550
          printInfo "access ChibiOS/NIL documentation via ${chibiosdir}edoc/nil/html/index.html\n"
551
        else
552
          issues=$((issues + 1))
553
          printError "could not generate ChibiOS/NIL documentation\n"
554
        fi
555
        ;;
556

    
557
      # open HTML documentation
558
      o)
559
        # ChibiOS/HAL: check if required files exis
560
        if [ -f ${chibiosdir}/doc/hal/html/index.html ]; then
561
          printInfo "open ChibiOS/HAL documentation\n"
562
          xdg-open ${chibiosdir}/doc/hal/html/index.html &> /dev/null &
563
        else
564
          issues=$((issues + 1))
565
          printError "could not open ChibiOS/HAL documentation\n"
566
        fi
567
        # ChibiOS/RT: check if required files exis
568
        if [ -f ${chibiosdir}/doc/rt/html/index.html ]; then
569
          printInfo "open ChibiOS/RT documentation\n"
570
          xdg-open ${chibiosdir}/doc/rt/html/index.html &> /dev/null &
571
        else
572
          issues=$((issues + 1))
573
          printError "could not open ChibiOS/RT documentation\n"
574
        fi
575
        # ChibiOS/NIL: check if required files exis
576
        if [ -f ${chibiosdir}/doc/nil/html/index.html ]; then
577
          printInfo "open ChibiOS/NIL documentation\n"
578
          xdg-open ${chibiosdir}/doc/nil/html/index.html &> /dev/null &
579
        else
580
          issues=$((issues + 1))
581
          printError "could not open ChibiOS/NIL documentation\n"
582
        fi
583
        ;;
584

    
585
      *) # sanity check (return error)
586
        printError "unexpected input: $userinput\n"; return -1;;
587
    esac
588

    
589
    if [ $issues -gt 0 ]; then
590
      return 3
591
    else
592
      return 0
593
    fi
594
  fi
595
}
596

    
597
### reset ChibiOS submodule and wipe directory #################################
598
# Resets the ChibiOS Git submodule and wipes the directory.
599
#
600
# usage:      wipeChibiOS
601
# arguments:  n/a
602
# return:     0
603
#                 No error or warning occurred.
604
#             1
605
#                 Warning: Submodule directory is already empty.
606
#             2
607
#                 Warning: Wiping aborted by user.
608
#             -1
609
#                 Error: Unexpected user input.
610
#
611
function wipeChibiOS {
612
  printInfo "reset and wipe Git submodule $kerneldir\n"
613
  local userdir=$(pwd)
614
  local kerneldir=$(dirname $(realpath ${BASH_SOURCE[0]}))
615
  local chibiosdir=${kerneldir}/ChibiOS
616
  local git_branch_patched="AMiRo-OS"
617

    
618
  # if the ChibiOS folder is empty
619
  if [ -z "$(ls -A $chibiosdir)" ]; then
620
    printInfo "$chibiosdir is alread empty\n"
621
    return 1
622
  else 
623
    # get some information from Git
624
    cd $kerneldir
625
    local git_basehash=($(git ls-tree -d HEAD $kerneldir)); git_basehash=${git_basehash[2]}
626
    cd $chibiosdir
627
    local git_branch_current=$(git rev-parse --abbrev-ref HEAD)
628
    local git_difftobase="$(git diff ${git_basehash}..HEAD)"
629
    local git_commits=$(git log --format=oneline ${git_basehash}..HEAD)
630
    local git_dirtyfiles=($(git ls-files -dmo --exclude-standard --exclude=/doc))
631
    cd $userdir
632
    local issues=0
633
    # if the HEAD is neither detached, nor is the current branch $git_branch_patched
634
    if [ "$git_branch_current" != "HEAD" ] && [ "$git_branch_current" != "$git_branch_patched" ]; then
635
      issues=$((issues + 1))
636
      printWarning "modifications to ChibiOS Git submodule detected\n"
637
    fi
638
    # if HEAD is ahead of submodule base commit but with more than just applied patches
639
    if [ -n "$git_difftobase" ] && [ -n "$(echo $git_commits | grep -Ev '\.patch applied$')" ]; then
640
      issues=$((issues + 1))
641
      printWarning "HEAD is ahead of submodule base by unexpected commits\n"
642
    fi
643
    # if there are untracked, modified, or deleted files
644
    if [ ${#git_dirtyfiles[@]} != 0 ]; then
645
      issues=$((issues + 1))
646
      printWarning "there are ${#git_dirtyfiles[@]} untracked, modified, or deleted files\n"
647
    fi
648
    if [ $issues -gt 0 ]; then
649
      local userinput=""
650
      printWarning "$issues issues detected. Do you want to continue? [y/n]\n"
651
      readUserInput "YyNn" userinput
652
      case "$userinput" in
653
        Y|y)
654
          ;;
655
        N|n)
656
          printfWarning "wiping ChibiOS Git submodule aborted by user\n"
657
          return 2
658
          ;;
659
        *) # sanity check (return error)
660
          printError "unexpected input: $userinput\n"; return -1;;
661
      esac
662
    fi
663

    
664
    # checkout base commit and delete all local branches
665
    cd $kerneldir
666
    git submodule update --force --checkout $kerneldir | tee -a $LOG_FILE
667
    cd $chibiosdir
668
    local git_branches=($(git for-each-ref --format="%(refname)"))
669
    for branch in $git_branches; do
670
      if [[ $branch = *"heads/"* ]]; then
671
        git branch -D ${branch##*/} | tee -a $LOG_FILE
672
      fi
673
    done
674
    cd $userdir
675

    
676
    # deinitialize ChibiOS submodule and delete any remaining files
677
    cd $kerneldir
678
    git submodule deinit -f $chibiosdir 2>&1 | tee -a $LOG_FILE
679
    rm -rf $chibiosdir/*
680
    cd $userdir
681

    
682
    return 0
683
  fi
684
}
685

    
686
### main function of this script ###############################################
687
# The kernel setup provides comfortable initialization, patching, documentation
688
# generation and cleanup for ChibiOS.
689
#
690
# usage:      see function printHelp
691
# arguments:  see function printHelp
692
# return:     0
693
#                 No error or warning occurred.
694
#
695
function main {
696
  # print welcome/info text if not suppressed
697
  if [[ $@ != *"--noinfo"* ]]; then
698
    printWelcomeText
699
  else
700
    printf "######################################################################\n"
701
  fi
702
  printf "\n"
703

    
704
  # if --help or -h was specified, print the help text and exit
705
  if [[ $@ == *"--help"* || $@ == *"-h"* ]]; then
706
    printHelp
707
    printf "\n"
708
    quitScript
709
  fi
710

    
711
  # set log file if specified
712
  if [[ $@ == *"--log"* ]] || [[ $@ == *"--LOG"* ]]; then
713
    # get the parameter (file name)
714
    local cmdidx=1
715
    while [[ ! "${!cmdidx}" = "--log"* ]] && [[ ! "${!cmdidx}" = "--LOG"* ]]; do
716
      cmdidx=$[cmdidx + 1]
717
    done
718
    local cmd="${!cmdidx}"
719
    local logfile=""
720
    if [[ "$cmd" = "--log="* ]] || [[ "$cmd" = "--LOG="* ]]; then
721
      logfile=${cmd#*=}
722
    else
723
      local filenameidx=$((cmdidx + 1))
724
      logfile="${!filenameidx}"
725
    fi
726
    # optionally force silent appending
727
    if [[ "$cmd" = "--LOG"* ]]; then
728
      setLogFile --option=c --quiet "$logfile" LOG_FILE
729
    else
730
      setLogFile "$logfile" LOG_FILE
731
      printf "\n"
732
    fi
733
  fi
734
  # log script name
735
  printLog "this is $(realpath ${BASH_SOURCE[0]})\n"
736

    
737
  # parse arguments
738
  local otherargs=()
739
  while [ $# -gt 0 ]; do
740
    if ( parseIsOption $1 ); then
741
      case "$1" in
742
        -h|--help) # already handled; ignore
743
          shift 1;;
744
        -i|--init)
745
           initChibiOS; printf "\n"; shift 1;;
746
        -p|--patch)
747
           patchChibiOS; printf "\n"; shift 1;;
748
        -d=*|--documentation=*)
749
           documentation "${1#*=}"; printf "\n"; shift 1;;
750
        -d|--documentation)
751
           if ( ! parseIsOption $2 ); then
752
             documentation "$2"; printf "\n"; shift 2
753
           else
754
             documentation; printf "\n"; shift 1
755
           fi;;
756
        -w|--wipe)
757
          wipeChibiOS; printf "\n"; shift 1;;
758
        -q|--quit)
759
          quitScript; shift 1;;
760
        --log=*|--LOG=*) # already handled; ignore
761
          shift 1;;
762
        --log|--LOG) # already handled; ignore
763
          shift 2;;
764
        --noinfo) # already handled; ignore
765
          shift 1;;
766
        *)
767
          printError "invalid option: $1\n"; shift 1;;
768
      esac
769
    else
770
      otherargs+=("$1")
771
      shift 1
772
    fi
773
  done
774

    
775
  # interactive menu
776
  while ( true ); do
777
    # main menu info prompt and selection
778
    printInfo "ChibiOS kernel setup main menu\n"
779
    printf "Please select one of the following actions:\n"
780
    printf "  [I] - initialize ChibiOS submodule\n"
781
    printf "  [P] - apply patches to ChibiOS\n"
782
    printf "  [D] - generate or open HTML documentation\n"
783
    printf "  [W] - wipe ChibiOS submodule\n"
784
    printf "  [Q] - quit this setup\n"
785
    local userinput=""
786
    readUserInput "IiPpDdWwQq" userinput
787
    printf "\n"
788

    
789
    # evaluate user selection
790
    case "$userinput" in
791
      I|i)
792
        initChibiOS; printf "\n";;
793
      P|p)
794
        patchChibiOS; printf "\n";;
795
      D|d)
796
        documentation; printf "\n";;
797
      W|w)
798
        wipeChibiOS; printf "\n";;
799
      Q|q)
800
        quitScript;;
801
      *) # sanity check (exit with error)
802
        printError "unexpected argument: $userinput\n";;
803
    esac
804
  done
805

    
806
  exit 0
807
}
808

    
809
################################################################################
810
# SCRIPT ENTRY POINT                                                           #
811
################################################################################
812

    
813
main "$@"