Statistics
| Branch: | Tag: | Revision:

amiro-blt / tools / compiler / GCC / gccsetup.sh @ 449d916a

History | View | Annotate | Download (32.9 KB)

1
################################################################################
2
# AMiRo-BLT is an bootloader and toolchain designed for the Autonomous Mini    #
3
# Robot (AMiRo) platform.                                                      #
4
# Copyright (C) 2016..2019  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 GCC setup!                      #\n"
281
  printf "#                                                                    #\n"
282
  printf "######################################################################\n"
283
  printf "#                                                                    #\n"
284
  printf "# Copyright (c) 2016..2019  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|--install] [-c|--change] [-q|--quit] [--log=<file>]\n"
307
  printf "\n"
308
  printf "options:  -h, --help\n"
309
  printf "              Print this help text.\n"
310
  printf "          -i, --install\n"
311
  printf "              Install another version.\n"
312
  printf "          -u, --uninstall\n"
313
  printf "              Unistall a version.\n"
314
  printf "          -c, --change\n"
315
  printf "              Change the default version.\n"
316
  printf "          -q, --quit\n"
317
  printf "              Quit the script.\n"
318
  printf "          --log=<file>\n"
319
  printf "              Specify a log file.\n"
320
}
321

    
322
### detect installed versions ##################################################
323
# Detect all installed version of arm-none-eabi-gcc, if any.
324
#
325
# usage:      detectInstalledVersions <binarray> <current> [<current_idx>]
326
# arguments:  <binarray>
327
#                 Array variable to store all detected binary paths to. 
328
#             <current>
329
#                 Variable to store the currently active binary to.
330
#             <current_idx>
331
#                 Index of the curretly selected version in the output array (<binarray>).
332
# return:     n/a
333
#
334
function detectInstalledVersions {
335
  local armgcc_command=$(command -v arm-none-eabi-gcc)
336
  local armgcc_commanddir=${HOME}/gcc-none-eabi
337
  local armgcc_currentbin=""
338
  local armgcc_installdir=${HOME}/gcc-none-eabi
339
  local armgcc_bins=()
340
  local armgcc_bincnt=0
341

    
342
  # check for already installed versions
343
  if [ -n "$armgcc_command" ]; then
344
    # follow the link to the actual binary
345
    armgcc_commanddir=$(dirname $armgcc_command)
346
    armgcc_currentbin=$armgcc_command
347
    while [ -L $armgcc_currentbin ]; do
348
      # differentiate between relative and absolute paths
349
      if [[ $(readlink $armgcc_currentbin) = /* ]]; then
350
        armgcc_currentbin=$(readlink $armgcc_currentbin)
351
      else
352
        armgcc_currentbin=$(realpath $(dirname $armgcc_currentbin)/$(readlink $armgcc_currentbin))
353
      fi
354
    done
355
    # the installation location is assumed to be two directories up
356
    armgcc_installdir=$(realpath $(dirname ${armgcc_currentbin})/../..)
357
    # list all detected instalations
358
    for dir in $(ls -d ${armgcc_installdir}/*/); do
359
      if [ -f ${dir}/bin/arm-none-eabi-gcc ]; then
360
        armgcc_bins[$armgcc_bincnt]=${dir}bin/arm-none-eabi-gcc
361
        armgcc_bincnt=$((armgcc_bincnt + 1))
362
      fi
363
    done
364

    
365
    # set the output variables
366
    eval "$1=(${armgcc_bins[*]})"
367
    eval $2="$armgcc_currentbin"
368
    if [ -n "$3" ]; then
369
      for (( bin=0; bin<${#armgcc_bins[@]}; ++bin )); do
370
        if [ ${armgcc_bins[bin]} = "$armgcc_currentbin" ]; then
371
          eval $3=$bin
372
        fi
373
      done
374
    fi
375
  else
376
    eval "$1=()"
377
    eval $2=""
378
    if [ -n "$3" ]; then
379
      eval $3=""
380
    fi
381
  fi
382
}
383

    
384
### install new version ########################################################
385
# Fetches an installation package from the internet, installs it and expands
386
# the $PATH environment variable (via .bashrc) if required.
387
#
388
# usage:      installNewVersion [-i|--install=<path>] [-l|--link=<path>]
389
# argumenst:  -i, --install <path>
390
#                 Path where to install the new version to.
391
#             -l, --link <path>
392
#                 Path where to create according links.
393
# return:     0
394
#                 No error or warnign occurred.
395
#             1
396
#                 Warning: Installation aborted by user.
397
#
398
function installNewVersion {
399
  local installbasedir=${HOME}/gcc-arm-embedded
400
  local linkdir="/usr/bin"
401

    
402
  # parse arguments
403
  local otherargs=()
404
  while [ $# -gt 0 ]; do
405
    if ( parseIsOption $1 ); then
406
      case "$1" in
407
        -i=*|--install=*)
408
          installbasedir=$(realpath "${1#*=}"); shift 1;;
409
        -i|--install)
410
          installbasedir="$2"; shift 2;;
411
        -l=*|--link=*)
412
          linkdir=$(realpath "${1#*=}"); shift 1;;
413
        -l|--link)
414
          linkdir="$2"; shift 2;;
415
        *) # sanity check (exit with error)
416
          printError "invalid option: $1\n"; shift 1;;
417
      esac
418
    else
419
      otherargs+=("$1")
420
      shift 1
421
    fi
422
  done
423

    
424
  # read download URL form user
425
  printLog "read installation url from user\n"
426
  local armgcc_downloadurl=""
427
  while [ -z "$armgcc_downloadurl" ]; do
428
    read -p "Download link for the installation file: " -e armgcc_downloadurl
429
    if [ -z "$armgcc_downloadurl" ]; then
430
      printWarning "installation aborted by user\n"
431
      return 1
432
    fi
433
    if [[ $armgcc_downloadurl != *".tar.bz2" ]]; then
434
      printWarning "please specify a .tar.bz2 file\n"
435
      armgcc_downloadurl=""
436
    fi
437
    if [ ! wget --spider $armgcc_downloadurl 2>/dev/null ]; then
438
      printWarning "$armgcc_downloadurl can not be reached\n"
439
      armgcc_downloadurl=""
440
    fi
441
  done
442
  printLog "user selected $armgcc_downloadurl\n"
443

    
444
  # if the file already exists, ask the user if it should be downloaded again
445
  local armgcc_tarball=$(basename "$armgcc_downloadurl")
446
  if [ -e "$armgcc_tarball" ]; then
447
    printWarning "$armgcc_tarball already exists. Delete and redownload? [y/n]\n"
448
    local userinput=""
449
    readUserInput "YyNn" userinput
450
    case "$userinput" in
451
      Y|y)
452
        rm "$armgcc_tarball"
453
        wget "$armgcc_downloadurl" | tee -a $LOG_FILE
454
        ;;
455
      N|n)
456
        ;;
457
      *) # sanity check (exit with error)
458
        printError "unexpected argument: $userinput\n";;
459
    esac
460
  else
461
    wget "$armgcc_downloadurl" | tee -a $LOG_FILE
462
  fi
463

    
464
  # extract tarball
465
  printInfo "extracting ${armgcc_tarball}...\n"
466
  tar -jxf "$armgcc_tarball" | tee -a $LOG_FILE
467
  local compilerdir=`tar --bzip2 -tf ${armgcc_tarball} | sed -e 's@/.*@@' | uniq`
468

    
469
  # install gcc arm embedded
470
  printLog "read installation directory from user\n"
471
  local installdir=""
472
  read -p "Installation directory: " -i ${installbasedir}/${compilerdir} -e installdir
473
  printLog "user selected $installdir\n"
474
  linkdir=$(dirname ${installdir})
475
  printLog "read link directory\n"
476
  read -p "Link directory: " -i $linkdir -e linkdir
477
  printLog "user selected $linkdir\n"
478
  # if the installation path already exists, ask user to overwrite
479
  if [ -d "$installdir" ]; then
480
    printWarning "$installdir already exists. Overwrite? [y/n]\n"
481
    local userinput=""
482
    readUserInput "YyNn" userinput
483
    case "$userinput" in
484
      Y|y)
485
        ;;
486
      N|n)
487
        printWarning "installation aborted by user\n"
488
        return 1
489
        ;;
490
      *) # sanity check (exit with error)
491
        printError "invalid option: $userinput\n";;
492
    esac
493
  # make sure the whole ínstallation path exists
494
  else
495
    while [ ! -d $(dirname "$installdir") ]; do
496
      local dir=$(dirname "$installdir") 
497
      while [ ! -d $(dirname "$dir") ]; do
498
        dir=$(dirname "$dir")
499
      done
500
      echo "mkdir $dir"
501
      mkdir "$dir"
502
    done
503
  fi
504
  # copy the extracted compiler folder
505
  cp -fR "$compilerdir" "$installdir"
506
  # make sure whole link path exists
507
  while [ ! -d "$linkdir" ]; do
508
    local dir="$linkdir"
509
    while [ ! -d $(dirname "$linkdir") ]; do
510
      dir=$(dirname "$dir")
511
    done
512
    mkdir "$dir"
513
  done
514
  # create / overwrite links
515
  local linkpath=$(realpath --relative-base=$linkdir ${installdir}/bin/)
516
  ls ${installdir}/bin/ | xargs -i ln -sf ${linkpath}/{} ${linkdir}/{}
517
  printInfo "default version set to $(arm-none-eabi-gcc -dumpversion)\n"
518

    
519
  # append the link directory to the PATH environment variable if required
520
  if [[ ! "$linkdir" = *"$PATH"* ]]; then
521
    local bashrc_file=${HOME}/.bashrc
522
    local bashrc_identifier="##### AMiRo ENVIRONMENT CONFIGURATION #####"
523
    local bashrc_note="# DO NOT EDIT THESE LINES MANUALLY!"
524
    local bashrc_entry="export PATH=\$PATH:$linkdir"
525

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

    
531
      # append a new entry to the BASHRC_FILE
532
      0)
533
        # make sure the last line is empty
534
        if [[ ! $(tail -1 $bashrc_file) =~ ^[\ \t]*$ ]]; then
535
          printf "\n" >> $bashrc_file
536
        fi
537
        # append text to file
538
        sed -i '$a'"$bashrc_identifier\n$bashrc_note\n$bashrc_entry\n$bashrc_identifier\n" $bashrc_file
539
        # print note
540
        printInfo "Your $bashrc_file has been updated. You need to source it to apply the changes in your environment.\n"
541
        read -p "  Understood!"
542
        ;;
543

    
544
      # extend the old entry
545
      2)
546
        # don't do anything if the line is already present
547
        local bashrc_entrylines=$(grep -x -n "$bashrc_entry" $bashrc_file | cut -f1 -d:) # string of line numbers
548
        bashrc_entrylines=(${bashrc_entrylines//"\n"/" "}) # array of line numbers
549
        if [[ ${#bashrc_entrylines[@]} = 0 ]]; then
550
          # insert the entry before the closing identifier
551
          sed -i "${bashrc_idlines[1]}"'i'"$bashrc_entry" $bashrc_file
552
          # print note
553
          printInfo "Your $bashrc_file has been updated. You need to source it to apply the changes in your environment.\n"
554
          read -p "  Understood!"
555
        elif [[ ${#bashrc_entrylines[@]} -eq 1 && ( ${bashrc_entrylines[0]} -lt ${bashrc_idlines[0]} || ${bashrc_entrylines[0]} -gt ${bashrc_idlines[1]} ) ]]; then
556
          # print an error that there is an entry at the wrong place
557
          printError "corrupted entry in your $bashrc_file detected\n"
558
          printf "The following entry was found at the wrong place:\n"
559
          printf "\n"
560
          printf "$bashrc_entry\n"
561
          printf "\n"
562
          printf "To fix this, delete the line and rerun this setup.\n"
563
          read -p "  Understood!"
564
        elif [[ ${#bashrc_entrylines[@]} -gt 1 ]]; then
565
          # print an error that there are multiple entries
566
          printError "corrupted entry in your $bashrc_file detected\n"
567
          printf "There are multiple identical entries in your $bashrc_file file.\n"
568
          printf "To fix it, make sure that it contains the following line exactly once:\n"
569
          printf "\n"
570
          printf "$bashrc_entry\n"
571
          printf "\n"
572
          read -p "  Understood!"
573
        fi
574
        ;;
575

    
576
      # error state (corrupted entry detected)
577
      *)
578
        printError "unable to append link directory to \$PATH variable\n"
579
        printf "There seems to be a broken entry in your $bashrc_file file.\n"
580
        printf "To fix it, make sure that the following line appears exactly twice and encloses your AMiRo related settings:\n"
581
        printf "\n"
582
        printf "$bashrc_identifier\n"
583
        printf "\n"
584
        read -p "  Understood!"
585
        ;;
586
    esac
587
  fi
588

    
589
  # clean up the current directory
590
  rm "$armgcc_tarball"
591
  rm -rf "$compilerdir"
592

    
593
  return 0
594
}
595

    
596
### uninstall a version ########################################################
597
# Select an installed version and uninstall it from the system.
598
#
599
# usage:      uninstallVersion <versions> <current_idx> <linkdir>
600
# arguments:  <version>
601
#                 Array of available versions (full path to binary).
602
#             <current_idx>
603
#                 Index of the currently selected version in the array.
604
#             <linkdir>
605
#                 Path where to delete old links.
606
# return:     0
607
#                 No error or warning occurred.
608
#             1
609
#                 Warning: Installation aborted by user.
610
#             -1
611
#                 Error: An exception occurred.
612
#
613
function uninstallVersion {
614
  local versions=("${!1}")
615
  local current_idx="$2"
616
  local linkdir="$3"
617

    
618
  # check whether at least two installations were detected
619
  if [ ${#versions[@]} -eq 0 ]; then
620
    printError "no installation detected\n"
621
    return -1
622
  else
623
    # print all available versions
624
    printInfo "choose the installation to uninstall to or type 'A' to abort:\n"
625
    for (( cnt=0; cnt<${#versions[@]}; ++cnt )); do
626
      if [ $cnt -eq $current_idx ]; then
627
        printf "*%3u: %s\n" $(($cnt + 1)) ${versions[$cnt]}
628
      else
629
        printf " %3u: %s\n" $(($cnt + 1)) ${versions[$cnt]}
630
      fi
631
    done
632

    
633
    # read user selection
634
    printLog "read user slection\n"
635
    local userinput=""
636
    while [ -z $userinput ] ; do
637
      read -p "your selection: " -e userinput
638
      printLog "user selection: $userinput\n"
639
      if [[ ! "$userinput" =~ ^[0-9]+$ ]] || [ ! "$userinput" -gt 0 ] || [ ! "$userinput" -le ${#versions[@]} ] && [[ ! "$userinput" =~ ^[Aa]$ ]]; then
640
        printWarning "Please enter an integer between 1 and ${#versions[@]} or 'A' to abort.\n"
641
        userinput=""
642
      fi
643
      if [ ${#versions[@]} -gt 1 ] && [ $((userinput - 1)) -eq $current_idx ]; then
644
        printWarning "Unable to uninstall currently selected version (as long as there are others).\n"
645
        userinput=""
646
      fi
647
    done
648

    
649
    if [[ "$userinput" =~ ^[Aa]$ ]]; then
650
      printWarning "aborted by user\n"
651
      return 1
652
    else
653
      local idx=$((userinput - 1))
654
      printf "\n"
655
      # prompt selected and aks user for confirmation
656
      printInfo "${versions[$idx]} will be removed. Continue? [y/n]\n"
657
      readUserInput "YyNn" userinput
658
      case "$userinput" in
659
        Y|y)
660
          ;;
661
        N|n)
662
          printWarning "uninstallation process aborted by user\n"
663
          return 1
664
          ;;
665
        *) # sanity check (exit with error)
666
          printError "invalid option: $userinput\n"
667
          return -1
668
          ;;
669
      esac
670
      # find and delete any links pointing to the version to be deleted
671
      for link in `find $linkdir -maxdepth 1 -type l`; do
672
        local l=$link
673
        # follow the link to the actual binary
674
        while [ -L $l ]; do
675
          # differentiate between relative and absolute paths
676
          if [[ $(readlink $l) = /* ]]; then
677
            l=$(readlink $l)
678
          else
679
            l=$(realpath $(dirname $l)/$(readlink $l))
680
          fi
681
        done
682
        # delete the link if it points to the version to be uninstalled
683
        if [ $(dirname $l) == $(dirname ${versions[$idx]}) ]; then
684
          rm $link
685
        fi
686
      done
687
      # delete the version directory (assumed to be one directory up)
688
      rm -rf $(realpath $(dirname ${versions[$idx]})/..)
689
      printInfo "${versions[$idx]} has been removed.\n"
690
    fi
691
  fi
692

    
693
  return 0
694
}
695

    
696
### change default version #####################################################
697
# Change the default arm-none-eabi-gcc version.
698
#
699
# usage:      changeDefaultVersion <versions> <linkdir>
700
# argumenst:  <versions>
701
#                 Array of available versions (full path to binary).
702
#             <linkdir>
703
#                 Path where to delete old and create new links.
704
# return:     0
705
#                 No error or warnign occurred.
706
#             -1
707
#                 Error: no installation detected.
708
#
709
function changeDefaultVersion {
710
  local versions=("${!1}")
711
  local linkdir="$2"
712

    
713
  # check whether an installation was detected
714
  if [ ${#versions[@]} -eq 0 ]; then
715
    printError "no installation detected\n"
716
    return -1
717
  else
718
    # print all available versions
719
    printInfo "choose the installation to switch to or type 'A' to abort:\n"
720
    for (( cnt=0; cnt<${#versions[@]}; ++cnt )); do
721
      printf "  %2u: %s\n" $(($cnt + 1)) ${versions[$cnt]}
722
    done
723

    
724
    # read user selection
725
    printLog "read user slection\n"
726
    local userinput=""
727
    while [[ ! "$userinput" =~ ^[0-9]+$ ]] || [ ! "$userinput" -gt 0 ] || [ ! "$userinput" -le ${#versions[@]} ] && [[ ! "$userinput" =~ ^[Aa]$ ]]; do
728
      read -p "your selection: " -e userinput
729
      printLog "user selection: $userinput\n"
730
      if [[ ! "$userinput" =~ ^[0-9]+$ ]] || [ ! "$userinput" -gt 0 ] || [ ! "$userinput" -le ${#versions[@]} ] && [[ ! "$userinput" =~ ^[Aa]$ ]]; then
731
        printWarning "Please enter an integer between 1 and ${#versions[@]} or 'A' to abort.\n"
732
      fi
733
    done
734

    
735
    if [[ "$userinput" =~ ^[Aa]$ ]]; then
736
      printWarning "aborted by user\n"
737
    else
738
      local idx=$((userinput - 1))
739
      # find and delete old links
740
      rm `find $linkdir -maxdepth 1 -type l | grep -Ev "*[0-9]\.[0-9]\.[0-9]"`
741
      # create new links with relative or absolute paths
742
      local bindir=$(dirname ${versions[$idx]})
743
      local linkpath=$(realpath --relative-base=$linkdir $bindir)
744
      ls $bindir | xargs -i ln -sf $linkpath/{} $linkdir/{}
745
      printInfo "default version set to $(arm-none-eabi-gcc -dumpversion)\n"
746
    fi
747
  fi
748

    
749
  return 0
750
}
751

    
752
### main function of this script ###############################################
753
# The IDE setup lets the user select an IDE of choice.
754
# As of now, only QtCreator is supported.
755
#
756
# usage:      see function printHelp
757
# arguments:  see function printHelp
758
# return:     0
759
#                 No error or warning occurred.
760
#
761
function main {
762
  # print welcome/info text if not suppressed
763
  if [[ $@ != *"--noinfo"* ]]; then
764
    printWelcomeText
765
  else
766
    printf "######################################################################\n"
767
  fi
768
  printf "\n"
769

    
770
  # if --help or -h was specified, print the help text and exit
771
  if [[ $@ == *"--help"* || $@ == *"-h"* ]]; then
772
    printHelp
773
    printf "\n"
774
    quitScript
775
  fi
776

    
777
  # set log file if specified
778
  if [[ $@ == *"--log"* ]] || [[ $@ == *"--LOG"* ]]; then
779
    # get the parameter (file name)
780
    local cmdidx=1
781
    while [[ ! "${!cmdidx}" = "--log"* ]] && [[ ! "${!cmdidx}" = "--LOG"* ]]; do
782
      cmdidx=$[cmdidx + 1]
783
    done
784
    local cmd="${!cmdidx}"
785
    local logfile=""
786
    if [[ "$cmd" = "--log="* ]] || [[ "$cmd" = "--LOG="* ]]; then
787
      logfile=${cmd#*=}
788
    else
789
      local filenameidx=$((cmdidx + 1))
790
      logfile="${!filenameidx}"
791
    fi
792
    # optionally force silent appending
793
    if [[ "$cmd" = "--LOG"* ]]; then
794
      setLogFile --option=c --quiet "$logfile" LOG_FILE
795
    else
796
      setLogFile "$logfile" LOG_FILE
797
      printf "\n"
798
    fi
799
  fi
800
  # log script name
801
  printLog "this is $(realpath ${BASH_SOURCE[0]})\n"
802

    
803
  # detect installed versions and inform user
804
  local installedversions=()
805
  local currentversion=""
806
  local currentversionidx="n/a"
807
  detectInstalledVersions installedversions currentversion currentversionidx
808
  case "${#installedversions[@]}" in
809
    0)
810
      printInfo "no installation has been detected\n";;
811
    1)
812
      printInfo "1 installation has been detected:\n";;
813
    *)
814
      printInfo "${#installedversions[@]} installations have been detected:\n";;
815
  esac
816
  for (( idx=0; idx<${#installedversions[@]}; ++idx )); do
817
    if [ ${installedversions[$idx]} = "$currentversion" ]; then
818
      printInfo "  * ${installedversions[$idx]}\n"
819
    else
820
      printInfo "    ${installedversions[$idx]}\n"
821
    fi
822
  done
823
  printf "\n"
824

    
825
  # parse arguments
826
  local otherargs=()
827
  while [ $# -gt 0 ]; do
828
    if ( parseIsOption $1 ); then
829
      case "$1" in
830
        -h|--help) # already handled; ignore
831
          shift 1;;
832
        -i|--install)
833
          if [ -z "$currentversion" ]; then
834
            installNewVersion
835
          else
836
            installNewVersion --install=$(realpath $(dirname $currentversion)/../..) --link=$(realpath $(dirname $currentversion)/../..)
837
          fi
838
          detectInstalledVersions installedversions currentversion currentversionidx
839
          printf "\n"; shift 1;;
840
        -u|--uninstall)
841
          if [ ! -z "$currentversion" ]; then
842
            uninstallVersion installedversions[@] $currentversionidx $(realpath $(dirname $currentversion)/../..)
843
            detectInstalledVersions installedversions currentversion currentversionidx
844
          else
845
            printError "no installation detected\n"
846
          fi
847
          printf "\n"; shift 1;;
848
        -c|--change)
849
          if [ ! -z "$currentversion" ]; then
850
            changeDefaultVersion installedversions[@] $(realpath $(dirname $currentversion)/../..)
851
          else
852
            printError "no installation detected\n"
853
          fi
854
          printf "\n"; shift 1;;
855
        -q|--quit)
856
          quitScript; shift 1;;
857
        --log=*|--LOG=*) # already handled; ignore
858
          shift 1;;
859
        --log|--LOG) # already handled; ignore
860
          shift 2;;
861
        --noinfo) # already handled; ignore
862
          shift 1;;
863
        *)
864
          printError "invalid option: $1\n"; shift 1;;
865
      esac
866
    else
867
      otherargs+=("$1")
868
      shift 1
869
    fi
870
  done
871

    
872
  # interactive menu
873
  while ( true ); do
874
    # main menu info prompt and selection
875
    printInfo "GCC setup main menu\n"
876
    printf "Please select one of the following actions:\n"
877
    printf "  [I] - install another version\n"
878
    printf "  [U] - uninstall a version\n"
879
    printf "  [C] - change default version\n"
880
    printf "  [Q] - quit this setup\n"
881
    local userinput=""
882
    readUserInput "IiUuCcQq" userinput
883
    printf "\n"
884

    
885
    # evaluate user selection
886
    case "$userinput" in
887
      I|i)
888
        if [ -z "$currentversion" ]; then
889
          installNewVersion
890
        else
891
          installNewVersion --install=$(realpath $(dirname $currentversion)/../..) --link=$(realpath $(dirname $currentversion)/../..)
892
        fi
893
        detectInstalledVersions installedversions currentversion currentversionidx
894
        printf "\n";;
895
      U|u)
896
        if [ ! -z "$currentversion" ]; then
897
          uninstallVersion installedversions[@] $currentversionidx $(realpath $(dirname $currentversion)/../..)
898
          detectInstalledVersions installedversions currentversion currentversionidx
899
        else
900
          printError "no installation detected\n"
901
        fi
902
        printf "\n";;
903
      C|c)
904
        if [ ! -z "$currentversion" ]; then
905
          changeDefaultVersion installedversions[@] $(realpath $(dirname $currentversion)/../..)
906
        else
907
          printError "no installation detected\n"
908
        fi
909
        printf "\n";;
910
      Q|q)
911
        quitScript;;
912
      *) # sanity check (exit with error)
913
        printError "unexpected argument: $userinput\n";;
914
    esac
915
  done
916

    
917
  exit 0
918
}
919

    
920
################################################################################
921
# SCRIPT ENTRY POINT                                                           #
922
################################################################################
923

    
924
main "$@"