Statistics
| Branch: | Tag: | Revision:

amiro-blt / tools / compiler / GCC / gccsetup.sh @ c9c97bb3

History | View | Annotate | Download (34.102 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
### check whether commands are available #######################################
267
# Checks whether the specified commands are available and can be executed.
268
#
269
# usage:      checkCommand [<command> <command> ...]
270
# arguments:  <command>
271
#                 Name of the command to check.
272
# return:     0
273
#                 All requested commands are available.
274
#             >0
275
#                 Number of requested commands that were not found.
276
#             -1
277
#                 No argument given.
278
#
279
function checkCommands {
280
  local status=0
281

    
282
  # return if no argument was specified
283
  if [ $# -eq 0 ]; then
284
    return -1
285
  fi
286

    
287
  # check all specified commands
288
  while [ $# -gt 0 ]; do
289
    command -v $1 &>/dev/null
290
    if [ $? -ne 0 ]; then
291
      printWarning "Command '$1' not available.\n"
292
      status=$((status + 1))
293
    fi
294
    shift 1
295
  done
296

    
297
  return $status
298
}
299

    
300
################################################################################
301
# SPECIFIC FUNCTIONS                                                           #
302
################################################################################
303

    
304
### print welcome text #########################################################
305
# Prints a welcome message to standard out.
306
#
307
# usage:      printWelcomeText
308
# arguments:  n/a
309
# return:     n/a
310
#
311
function printWelcomeText {
312
  printf "######################################################################\n"
313
  printf "#                                                                    #\n"
314
  printf "#                     Welcome to the GCC setup!                      #\n"
315
  printf "#                                                                    #\n"
316
  printf "######################################################################\n"
317
  printf "#                                                                    #\n"
318
  printf "# Copyright (c) 2016..2019  Thomas Schöpping                         #\n"
319
  printf "#                                                                    #\n"
320
  printf "# This is free software; see the source for copying conditions.      #\n"
321
  printf "# There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR  #\n"
322
  printf "# A PARTICULAR PURPOSE. The development of this software was         #\n"
323
  printf "# supported by the Excellence Cluster EXC 227 Cognitive Interaction  #\n"
324
  printf "# Technology. The Excellence Cluster EXC 227 is a grant of the       #\n"
325
  printf "# Deutsche Forschungsgemeinschaft (DFG) in the context of the German #\n"
326
  printf "# Excellence Initiative.                                             #\n"
327
  printf "#                                                                    #\n"
328
  printf "######################################################################\n"
329
}
330

    
331
### print help #################################################################
332
# Prints a help text to standard out.
333
#
334
# usage:      printHelp
335
# arguments:  n/a
336
# return:     n/a
337
#
338
function printHelp {
339
  printInfo "printing help text\n"
340
  printf "usage:    $(basename ${BASH_SOURCE[0]}) [-h|--help] [-i|--install] [-c|--change] [-q|--quit] [--log=<file>]\n"
341
  printf "\n"
342
  printf "options:  -h, --help\n"
343
  printf "              Print this help text.\n"
344
  printf "          -i, --install\n"
345
  printf "              Install another version.\n"
346
  printf "          -u, --uninstall\n"
347
  printf "              Unistall a version.\n"
348
  printf "          -c, --change\n"
349
  printf "              Change the default version.\n"
350
  printf "          -q, --quit\n"
351
  printf "              Quit the script.\n"
352
  printf "          --log=<file>\n"
353
  printf "              Specify a log file.\n"
354
}
355

    
356
### detect installed versions ##################################################
357
# Detect all installed version of arm-none-eabi-gcc, if any.
358
#
359
# usage:      detectInstalledVersions <binarray> <current> [<current_idx>]
360
# arguments:  <binarray>
361
#                 Array variable to store all detected binary paths to. 
362
#             <current>
363
#                 Variable to store the currently active binary to.
364
#             <current_idx>
365
#                 Index of the curretly selected version in the output array (<binarray>).
366
# return:     n/a
367
#
368
function detectInstalledVersions {
369
  local armgcc_command=$(command -v arm-none-eabi-gcc)
370
  local armgcc_commanddir=${HOME}/gcc-none-eabi
371
  local armgcc_currentbin=""
372
  local armgcc_installdir=${HOME}/gcc-none-eabi
373
  local armgcc_bins=()
374
  local armgcc_bincnt=0
375

    
376
  # check for already installed versions
377
  if [ -n "$armgcc_command" ]; then
378
    # follow the link to the actual binary
379
    armgcc_commanddir=$(dirname $armgcc_command)
380
    armgcc_currentbin=$armgcc_command
381
    while [ -L $armgcc_currentbin ]; do
382
      # differentiate between relative and absolute paths
383
      if [[ $(readlink $armgcc_currentbin) = /* ]]; then
384
        armgcc_currentbin=$(readlink $armgcc_currentbin)
385
      else
386
        armgcc_currentbin=$(realpath $(dirname $armgcc_currentbin)/$(readlink $armgcc_currentbin))
387
      fi
388
    done
389
    # the installation location is assumed to be two directories up
390
    armgcc_installdir=$(realpath $(dirname ${armgcc_currentbin})/../..)
391
    # list all detected instalations
392
    for dir in $(ls -d ${armgcc_installdir}/*/); do
393
      if [ -f ${dir}/bin/arm-none-eabi-gcc ]; then
394
        armgcc_bins[$armgcc_bincnt]=${dir}bin/arm-none-eabi-gcc
395
        armgcc_bincnt=$((armgcc_bincnt + 1))
396
      fi
397
    done
398

    
399
    # set the output variables
400
    eval "$1=(${armgcc_bins[*]})"
401
    eval $2="$armgcc_currentbin"
402
    if [ -n "$3" ]; then
403
      for (( bin=0; bin<${#armgcc_bins[@]}; ++bin )); do
404
        if [ ${armgcc_bins[bin]} = "$armgcc_currentbin" ]; then
405
          eval $3=$bin
406
        fi
407
      done
408
    fi
409
  else
410
    eval "$1=()"
411
    eval $2=""
412
    if [ -n "$3" ]; then
413
      eval $3=""
414
    fi
415
  fi
416
}
417

    
418
### install new version ########################################################
419
# Fetches an installation package from the internet, installs it and expands
420
# the $PATH environment variable (via .bashrc) if required.
421
#
422
# usage:      installNewVersion [-i|--install=<path>] [-l|--link=<path>]
423
# argumenst:  -i, --install <path>
424
#                 Path where to install the new version to.
425
#             -l, --link <path>
426
#                 Path where to create according links.
427
# return:     0
428
#                 No error or warnign occurred.
429
#             1
430
#                 Warning: Installation aborted by user.
431
#             -1
432
#                 Error: specified URL can not be reached.
433
#             -2
434
#                 Error: Missing dependecny.
435
#
436
function installNewVersion {
437
  local installbasedir=${HOME}/gcc-arm-embedded
438
  local linkdir="/usr/bin"
439

    
440
  # check dependencies
441
  checkCommands wget
442
  if [ $? -ne 0 ]; then
443
    printError "Missing dependencies detected.\n"
444
    return -2
445
  fi
446

    
447
  # parse arguments
448
  local otherargs=()
449
  while [ $# -gt 0 ]; do
450
    if ( parseIsOption $1 ); then
451
      case "$1" in
452
        -i=*|--install=*)
453
          installbasedir=$(realpath "${1#*=}"); shift 1;;
454
        -i|--install)
455
          installbasedir="$2"; shift 2;;
456
        -l=*|--link=*)
457
          linkdir=$(realpath "${1#*=}"); shift 1;;
458
        -l|--link)
459
          linkdir="$2"; shift 2;;
460
        *) # sanity check (exit with error)
461
          printError "invalid option: $1\n"; shift 1;;
462
      esac
463
    else
464
      otherargs+=("$1")
465
      shift 1
466
    fi
467
  done
468

    
469
  # read download URL form user
470
  printLog "read installation url from user\n"
471
  local armgcc_downloadurl=""
472
  while [ -z "$armgcc_downloadurl" ]; do
473
    read -p "Download link for the installation file: " -e armgcc_downloadurl
474
    if [ -z "$armgcc_downloadurl" ]; then
475
      printWarning "installation aborted by user\n"
476
      return 1
477
    fi
478
    # check whether url is valid
479
    wget --spider -r "$armgcc_downloadurl" &>/dev/null
480
    if [ $? -ne 0 ]; then
481
      printError "'$armgcc_downloadurl' can not be reached\n"
482
      return -1
483
    fi
484
  done
485
  printLog "user selected $armgcc_downloadurl\n"
486

    
487
  # if the file already exists, ask the user if it should be downloaded again
488
  local armgcc_tarball=$(basename $(wget --spider -r "$armgcc_downloadurl" 2>&1 | \
489
                                    grep "^--" | \
490
                                    tail -n 1 | \
491
                                    awk '{print $NF}'))
492
  if [ -f "$armgcc_tarball" ]; then
493
    printWarning "$armgcc_tarball already exists. Delete and redownload? [y/n]\n"
494
    local userinput=""
495
    readUserInput "YyNn" userinput
496
    case "$userinput" in
497
      Y|y)
498
        rm "$armgcc_tarball"
499
        wget "$armgcc_downloadurl" -O "$armgcc_tarball" | tee -a $LOG_FILE
500
        ;;
501
      N|n)
502
        ;;
503
      *) # sanity check (exit with error)
504
        printError "unexpected argument: $userinput\n";;
505
    esac
506
  else
507
    wget "$armgcc_downloadurl" -O "$armgcc_tarball" | tee -a $LOG_FILE
508
  fi
509

    
510
  # extract tarball
511
  printInfo "extracting ${armgcc_tarball}...\n"
512
  tar -jxf "$armgcc_tarball" | tee -a $LOG_FILE
513
  local compilerdir=`tar --bzip2 -tf ${armgcc_tarball} | sed -e 's@/.*@@' | uniq`
514

    
515
  # install gcc arm embedded
516
  printLog "read installation directory from user\n"
517
  local installdir=""
518
  read -p "Installation directory: " -i ${installbasedir}/${compilerdir} -e installdir
519
  printLog "user selected $installdir\n"
520
  linkdir=$(dirname ${installdir})
521
  printLog "read link directory\n"
522
  read -p "Link directory: " -i $linkdir -e linkdir
523
  printLog "user selected $linkdir\n"
524
  # if the installation path already exists, ask user to overwrite
525
  if [ -d "$installdir" ]; then
526
    printWarning "$installdir already exists. Overwrite? [y/n]\n"
527
    local userinput=""
528
    readUserInput "YyNn" userinput
529
    case "$userinput" in
530
      Y|y)
531
        ;;
532
      N|n)
533
        printWarning "installation aborted by user\n"
534
        return 1
535
        ;;
536
      *) # sanity check (exit with error)
537
        printError "invalid option: $userinput\n";;
538
    esac
539
  # make sure the whole ínstallation path exists
540
  else
541
    while [ ! -d $(dirname "$installdir") ]; do
542
      local dir=$(dirname "$installdir") 
543
      while [ ! -d $(dirname "$dir") ]; do
544
        dir=$(dirname "$dir")
545
      done
546
      echo "mkdir $dir"
547
      mkdir "$dir"
548
    done
549
  fi
550
  # copy the extracted compiler folder
551
  cp -fR "$compilerdir" "$installdir"
552
  # make sure whole link path exists
553
  while [ ! -d "$linkdir" ]; do
554
    local dir="$linkdir"
555
    while [ ! -d $(dirname "$linkdir") ]; do
556
      dir=$(dirname "$dir")
557
    done
558
    mkdir "$dir"
559
  done
560
  # create / overwrite links
561
  local linkpath=$(realpath --relative-base=$linkdir ${installdir}/bin/)
562
  ls ${installdir}/bin/ | xargs -i ln -sf ${linkpath}/{} ${linkdir}/{}
563
  printInfo "default version set to $(arm-none-eabi-gcc -dumpversion)\n"
564

    
565
  # append the link directory to the PATH environment variable if required
566
  if [[ ! "$linkdir" = *"$PATH"* ]]; then
567
    local bashrc_file=${HOME}/.bashrc
568
    local bashrc_identifier="##### AMiRo ENVIRONMENT CONFIGURATION #####"
569
    local bashrc_note="# DO NOT EDIT THESE LINES MANUALLY!"
570
    local bashrc_entry="export PATH=\$PATH:$linkdir"
571

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

    
577
      # append a new entry to the BASHRC_FILE
578
      0)
579
        # make sure the last line is empty
580
        if [[ ! $(tail -1 $bashrc_file) =~ ^[\ \t]*$ ]]; then
581
          printf "\n" >> $bashrc_file
582
        fi
583
        # append text to file
584
        sed -i '$a'"$bashrc_identifier\n$bashrc_note\n$bashrc_entry\n$bashrc_identifier\n" $bashrc_file
585
        # print note
586
        printInfo "Your $bashrc_file has been updated. You need to source it to apply the changes in your environment.\n"
587
        read -p "  Understood!"
588
        ;;
589

    
590
      # extend the old entry
591
      2)
592
        # don't do anything if the line is already present
593
        local bashrc_entrylines=$(grep -x -n "$bashrc_entry" $bashrc_file | cut -f1 -d:) # string of line numbers
594
        bashrc_entrylines=(${bashrc_entrylines//"\n"/" "}) # array of line numbers
595
        if [[ ${#bashrc_entrylines[@]} = 0 ]]; then
596
          # insert the entry before the closing identifier
597
          sed -i "${bashrc_idlines[1]}"'i'"$bashrc_entry" $bashrc_file
598
          # print note
599
          printInfo "Your $bashrc_file has been updated. You need to source it to apply the changes in your environment.\n"
600
          read -p "  Understood!"
601
        elif [[ ${#bashrc_entrylines[@]} -eq 1 && ( ${bashrc_entrylines[0]} -lt ${bashrc_idlines[0]} || ${bashrc_entrylines[0]} -gt ${bashrc_idlines[1]} ) ]]; then
602
          # print an error that there is an entry at the wrong place
603
          printError "corrupted entry in your $bashrc_file detected\n"
604
          printf "The following entry was found at the wrong place:\n"
605
          printf "\n"
606
          printf "$bashrc_entry\n"
607
          printf "\n"
608
          printf "To fix this, delete the line and rerun this setup.\n"
609
          read -p "  Understood!"
610
        elif [[ ${#bashrc_entrylines[@]} -gt 1 ]]; then
611
          # print an error that there are multiple entries
612
          printError "corrupted entry in your $bashrc_file detected\n"
613
          printf "There are multiple identical entries in your $bashrc_file file.\n"
614
          printf "To fix it, make sure that it contains the following line exactly once:\n"
615
          printf "\n"
616
          printf "$bashrc_entry\n"
617
          printf "\n"
618
          read -p "  Understood!"
619
        fi
620
        ;;
621

    
622
      # error state (corrupted entry detected)
623
      *)
624
        printError "unable to append link directory to \$PATH variable\n"
625
        printf "There seems to be a broken entry in your $bashrc_file file.\n"
626
        printf "To fix it, make sure that the following line appears exactly twice and encloses your AMiRo related settings:\n"
627
        printf "\n"
628
        printf "$bashrc_identifier\n"
629
        printf "\n"
630
        read -p "  Understood!"
631
        ;;
632
    esac
633
  fi
634

    
635
  # clean up the current directory
636
  rm "$armgcc_tarball"
637
  rm -rf "$compilerdir"
638

    
639
  return 0
640
}
641

    
642
### uninstall a version ########################################################
643
# Select an installed version and uninstall it from the system.
644
#
645
# usage:      uninstallVersion <versions> <current_idx> <linkdir>
646
# arguments:  <version>
647
#                 Array of available versions (full path to binary).
648
#             <current_idx>
649
#                 Index of the currently selected version in the array.
650
#             <linkdir>
651
#                 Path where to delete old links.
652
# return:     0
653
#                 No error or warning occurred.
654
#             1
655
#                 Warning: Installation aborted by user.
656
#             -1
657
#                 Error: An exception occurred.
658
#
659
function uninstallVersion {
660
  local versions=("${!1}")
661
  local current_idx="$2"
662
  local linkdir="$3"
663

    
664
  # check whether at least two installations were detected
665
  if [ ${#versions[@]} -eq 0 ]; then
666
    printError "no installation detected\n"
667
    return -1
668
  else
669
    # print all available versions
670
    printInfo "choose the installation to uninstall to or type 'A' to abort:\n"
671
    for (( cnt=0; cnt<${#versions[@]}; ++cnt )); do
672
      if [ $cnt -eq $current_idx ]; then
673
        printf "*%3u: %s\n" $(($cnt + 1)) ${versions[$cnt]}
674
      else
675
        printf " %3u: %s\n" $(($cnt + 1)) ${versions[$cnt]}
676
      fi
677
    done
678

    
679
    # read user selection
680
    printLog "read user slection\n"
681
    local userinput=""
682
    while [ -z $userinput ] ; do
683
      read -p "your selection: " -e userinput
684
      printLog "user selection: $userinput\n"
685
      if [[ ! "$userinput" =~ ^[0-9]+$ ]] || [ ! "$userinput" -gt 0 ] || [ ! "$userinput" -le ${#versions[@]} ] && [[ ! "$userinput" =~ ^[Aa]$ ]]; then
686
        printWarning "Please enter an integer between 1 and ${#versions[@]} or 'A' to abort.\n"
687
        userinput=""
688
      fi
689
      if [ ${#versions[@]} -gt 1 ] && [ $((userinput - 1)) -eq $current_idx ]; then
690
        printWarning "Unable to uninstall currently selected version (as long as there are others).\n"
691
        userinput=""
692
      fi
693
    done
694

    
695
    if [[ "$userinput" =~ ^[Aa]$ ]]; then
696
      printWarning "aborted by user\n"
697
      return 1
698
    else
699
      local idx=$((userinput - 1))
700
      printf "\n"
701
      # prompt selected and aks user for confirmation
702
      printInfo "${versions[$idx]} will be removed. Continue? [y/n]\n"
703
      readUserInput "YyNn" userinput
704
      case "$userinput" in
705
        Y|y)
706
          ;;
707
        N|n)
708
          printWarning "uninstallation process aborted by user\n"
709
          return 1
710
          ;;
711
        *) # sanity check (exit with error)
712
          printError "invalid option: $userinput\n"
713
          return -1
714
          ;;
715
      esac
716
      # find and delete any links pointing to the version to be deleted
717
      for link in `find $linkdir -maxdepth 1 -type l`; do
718
        local l=$link
719
        # follow the link to the actual binary
720
        while [ -L $l ]; do
721
          # differentiate between relative and absolute paths
722
          if [[ $(readlink $l) = /* ]]; then
723
            l=$(readlink $l)
724
          else
725
            l=$(realpath $(dirname $l)/$(readlink $l))
726
          fi
727
        done
728
        # delete the link if it points to the version to be uninstalled
729
        if [ $(dirname $l) == $(dirname ${versions[$idx]}) ]; then
730
          rm $link
731
        fi
732
      done
733
      # delete the version directory (assumed to be one directory up)
734
      rm -rf $(realpath $(dirname ${versions[$idx]})/..)
735
      printInfo "${versions[$idx]} has been removed.\n"
736
    fi
737
  fi
738

    
739
  return 0
740
}
741

    
742
### change default version #####################################################
743
# Change the default arm-none-eabi-gcc version.
744
#
745
# usage:      changeDefaultVersion <versions> <linkdir>
746
# argumenst:  <versions>
747
#                 Array of available versions (full path to binary).
748
#             <linkdir>
749
#                 Path where to delete old and create new links.
750
# return:     0
751
#                 No error or warnign occurred.
752
#             -1
753
#                 Error: no installation detected.
754
#
755
function changeDefaultVersion {
756
  local versions=("${!1}")
757
  local linkdir="$2"
758

    
759
  # check whether an installation was detected
760
  if [ ${#versions[@]} -eq 0 ]; then
761
    printError "no installation detected\n"
762
    return -1
763
  else
764
    # print all available versions
765
    printInfo "choose the installation to switch to or type 'A' to abort:\n"
766
    for (( cnt=0; cnt<${#versions[@]}; ++cnt )); do
767
      printf "  %2u: %s\n" $(($cnt + 1)) ${versions[$cnt]}
768
    done
769

    
770
    # read user selection
771
    printLog "read user slection\n"
772
    local userinput=""
773
    while [[ ! "$userinput" =~ ^[0-9]+$ ]] || [ ! "$userinput" -gt 0 ] || [ ! "$userinput" -le ${#versions[@]} ] && [[ ! "$userinput" =~ ^[Aa]$ ]]; do
774
      read -p "your selection: " -e userinput
775
      printLog "user selection: $userinput\n"
776
      if [[ ! "$userinput" =~ ^[0-9]+$ ]] || [ ! "$userinput" -gt 0 ] || [ ! "$userinput" -le ${#versions[@]} ] && [[ ! "$userinput" =~ ^[Aa]$ ]]; then
777
        printWarning "Please enter an integer between 1 and ${#versions[@]} or 'A' to abort.\n"
778
      fi
779
    done
780

    
781
    if [[ "$userinput" =~ ^[Aa]$ ]]; then
782
      printWarning "aborted by user\n"
783
    else
784
      local idx=$((userinput - 1))
785
      # find and delete old links
786
      rm `find $linkdir -maxdepth 1 -type l | grep -Ev "*[0-9]\.[0-9]\.[0-9]"`
787
      # create new links with relative or absolute paths
788
      local bindir=$(dirname ${versions[$idx]})
789
      local linkpath=$(realpath --relative-base=$linkdir $bindir)
790
      ls $bindir | xargs -i ln -sf $linkpath/{} $linkdir/{}
791
      printInfo "default version set to $(arm-none-eabi-gcc -dumpversion)\n"
792
    fi
793
  fi
794

    
795
  return 0
796
}
797

    
798
### main function of this script ###############################################
799
# The IDE setup lets the user select an IDE of choice.
800
# As of now, only QtCreator is supported.
801
#
802
# usage:      see function printHelp
803
# arguments:  see function printHelp
804
# return:     0
805
#                 No error or warning occurred.
806
#
807
function main {
808
  # print welcome/info text if not suppressed
809
  if [[ $@ != *"--noinfo"* ]]; then
810
    printWelcomeText
811
  else
812
    printf "######################################################################\n"
813
  fi
814
  printf "\n"
815

    
816
  # if --help or -h was specified, print the help text and exit
817
  if [[ $@ == *"--help"* || $@ == *"-h"* ]]; then
818
    printHelp
819
    printf "\n"
820
    quitScript
821
  fi
822

    
823
  # set log file if specified
824
  if [[ $@ == *"--log"* ]] || [[ $@ == *"--LOG"* ]]; then
825
    # get the parameter (file name)
826
    local cmdidx=1
827
    while [[ ! "${!cmdidx}" = "--log"* ]] && [[ ! "${!cmdidx}" = "--LOG"* ]]; do
828
      cmdidx=$[cmdidx + 1]
829
    done
830
    local cmd="${!cmdidx}"
831
    local logfile=""
832
    if [[ "$cmd" = "--log="* ]] || [[ "$cmd" = "--LOG="* ]]; then
833
      logfile=${cmd#*=}
834
    else
835
      local filenameidx=$((cmdidx + 1))
836
      logfile="${!filenameidx}"
837
    fi
838
    # optionally force silent appending
839
    if [[ "$cmd" = "--LOG"* ]]; then
840
      setLogFile --option=c --quiet "$logfile" LOG_FILE
841
    else
842
      setLogFile "$logfile" LOG_FILE
843
      printf "\n"
844
    fi
845
  fi
846
  # log script name
847
  printLog "this is $(realpath ${BASH_SOURCE[0]})\n"
848

    
849
  # detect installed versions and inform user
850
  local installedversions=()
851
  local currentversion=""
852
  local currentversionidx="n/a"
853
  detectInstalledVersions installedversions currentversion currentversionidx
854
  case "${#installedversions[@]}" in
855
    0)
856
      printInfo "no installation has been detected\n";;
857
    1)
858
      printInfo "1 installation has been detected:\n";;
859
    *)
860
      printInfo "${#installedversions[@]} installations have been detected:\n";;
861
  esac
862
  for (( idx=0; idx<${#installedversions[@]}; ++idx )); do
863
    if [ ${installedversions[$idx]} = "$currentversion" ]; then
864
      printInfo "  * ${installedversions[$idx]}\n"
865
    else
866
      printInfo "    ${installedversions[$idx]}\n"
867
    fi
868
  done
869
  printf "\n"
870

    
871
  # parse arguments
872
  local otherargs=()
873
  while [ $# -gt 0 ]; do
874
    if ( parseIsOption $1 ); then
875
      case "$1" in
876
        -h|--help) # already handled; ignore
877
          shift 1;;
878
        -i|--install)
879
          if [ -z "$currentversion" ]; then
880
            installNewVersion
881
          else
882
            installNewVersion --install=$(realpath $(dirname $currentversion)/../..) --link=$(realpath $(dirname $currentversion)/../..)
883
          fi
884
          detectInstalledVersions installedversions currentversion currentversionidx
885
          printf "\n"; shift 1;;
886
        -u|--uninstall)
887
          if [ ! -z "$currentversion" ]; then
888
            uninstallVersion installedversions[@] $currentversionidx $(realpath $(dirname $currentversion)/../..)
889
            detectInstalledVersions installedversions currentversion currentversionidx
890
          else
891
            printError "no installation detected\n"
892
          fi
893
          printf "\n"; shift 1;;
894
        -c|--change)
895
          if [ ! -z "$currentversion" ]; then
896
            changeDefaultVersion installedversions[@] $(realpath $(dirname $currentversion)/../..)
897
          else
898
            printError "no installation detected\n"
899
          fi
900
          printf "\n"; shift 1;;
901
        -q|--quit)
902
          quitScript; shift 1;;
903
        --log=*|--LOG=*) # already handled; ignore
904
          shift 1;;
905
        --log|--LOG) # already handled; ignore
906
          shift 2;;
907
        --noinfo) # already handled; ignore
908
          shift 1;;
909
        *)
910
          printError "invalid option: $1\n"; shift 1;;
911
      esac
912
    else
913
      otherargs+=("$1")
914
      shift 1
915
    fi
916
  done
917

    
918
  # interactive menu
919
  while ( true ); do
920
    # main menu info prompt and selection
921
    printInfo "GCC setup main menu\n"
922
    printf "Please select one of the following actions:\n"
923
    printf "  [I] - install another version\n"
924
    printf "  [U] - uninstall a version\n"
925
    printf "  [C] - change default version\n"
926
    printf "  [Q] - quit this setup\n"
927
    local userinput=""
928
    readUserInput "IiUuCcQq" userinput
929
    printf "\n"
930

    
931
    # evaluate user selection
932
    case "$userinput" in
933
      I|i)
934
        if [ -z "$currentversion" ]; then
935
          installNewVersion
936
        else
937
          installNewVersion --install=$(realpath $(dirname $currentversion)/../..) --link=$(realpath $(dirname $currentversion)/../..)
938
        fi
939
        detectInstalledVersions installedversions currentversion currentversionidx
940
        printf "\n";;
941
      U|u)
942
        if [ ! -z "$currentversion" ]; then
943
          uninstallVersion installedversions[@] $currentversionidx $(realpath $(dirname $currentversion)/../..)
944
          detectInstalledVersions installedversions currentversion currentversionidx
945
        else
946
          printError "no installation detected\n"
947
        fi
948
        printf "\n";;
949
      C|c)
950
        if [ ! -z "$currentversion" ]; then
951
          changeDefaultVersion installedversions[@] $(realpath $(dirname $currentversion)/../..)
952
        else
953
          printError "no installation detected\n"
954
        fi
955
        printf "\n";;
956
      Q|q)
957
        quitScript;;
958
      *) # sanity check (exit with error)
959
        printError "unexpected argument: $userinput\n";;
960
    esac
961
  done
962

    
963
  exit 0
964
}
965

    
966
################################################################################
967
# SCRIPT ENTRY POINT                                                           #
968
################################################################################
969

    
970
main "$@"