Statistics
| Branch: | Tag: | Revision:

amiro-blt / tools / compiler / GCC / gccsetup.sh @ 9bfc7c44

History | View | Annotate | Download (34.657 KB)

1 0a42f078 Thomas Schöpping
################################################################################
2
# AMiRo-BLT is an bootloader and toolchain designed for the Autonomous Mini    #
3
# Robot (AMiRo) platform.                                                      #
4 449d916a Thomas Schöpping
# Copyright (C) 2016..2019  Thomas Schöpping et al.                            #
5 0a42f078 Thomas Schöpping
#                                                                              #
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 3719a40a Thomas Schöpping
  printInfo "exiting $(realpath ${BASH_SOURCE[0]})\n"
110
  printf "\n"
111 0a42f078 Thomas Schöpping
  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 0dc9f2f9 Thomas Schöpping
#                 Possible values are 'a', 'c', 'r' and 'n'.
173
#                 - a: append (starts with a separator)
174
#                 - c: continue (does not insert a seperator)
175 0a42f078 Thomas Schöpping
#                 - 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 0dc9f2f9 Thomas Schöpping
      a|c)
231 0a42f078 Thomas Schöpping
        if [ $quiet = false ]; then
232
          printInfo "appending log to $filepath\n"
233
        fi
234 0dc9f2f9 Thomas Schöpping
        if [ $option != c ]; then
235
          printf "\n" >> $filepath
236
          printf "######################################################################\n" >> $filepath
237
          printf "\n" >> $filepath
238
        fi
239 0a42f078 Thomas Schöpping
        ;;
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 fad4c1e7 Thomas Schöpping
### check whether commands are available #######################################
267
# Checks whether the specified commands are available and can be executed.
268
#
269 e687187f Thomas Schöpping
# usage:      checkCommands [<command> <command> ...]
270 fad4c1e7 Thomas Schöpping
# 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 0a42f078 Thomas Schöpping
################################################################################
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 449d916a Thomas Schöpping
  printf "# Copyright (c) 2016..2019  Thomas Schöpping                         #\n"
319 0a42f078 Thomas Schöpping
  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 316a2b34 Thomas Schöpping
  printf "          -u, --uninstall\n"
347
  printf "              Unistall a version.\n"
348 0a42f078 Thomas Schöpping
  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 316a2b34 Thomas Schöpping
# usage:      detectInstalledVersions <binarray> <current> [<current_idx>]
360 0a42f078 Thomas Schöpping
# arguments:  <binarray>
361
#                 Array variable to store all detected binary paths to. 
362
#             <current>
363
#                 Variable to store the currently active binary to.
364 316a2b34 Thomas Schöpping
#             <current_idx>
365
#                 Index of the curretly selected version in the output array (<binarray>).
366 0a42f078 Thomas Schöpping
# 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 316a2b34 Thomas Schöpping
      # 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 0a42f078 Thomas Schöpping
    done
389
    # the installation location is assumed to be two directories up
390 316a2b34 Thomas Schöpping
    armgcc_installdir=$(realpath $(dirname ${armgcc_currentbin})/../..)
391 0a42f078 Thomas Schöpping
    # 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 316a2b34 Thomas Schöpping
    # 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 0a42f078 Thomas Schöpping
}
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 c9c97bb3 Thomas Schöpping
#             -1
432 2880bac8 Thomas Schöpping
#                 Error: specified URL can not be reached.
433 c9c97bb3 Thomas Schöpping
#             -2
434
#                 Error: Missing dependecny.
435 0a42f078 Thomas Schöpping
#
436
function installNewVersion {
437
  local installbasedir=${HOME}/gcc-arm-embedded
438
  local linkdir="/usr/bin"
439
440 c9c97bb3 Thomas Schöpping
  # check dependencies
441
  checkCommands wget
442
  if [ $? -ne 0 ]; then
443
    printError "Missing dependencies detected.\n"
444
    return -2
445
  fi
446
447 0a42f078 Thomas Schöpping
  # 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 73410535 Thomas Schöpping
  printf "In order to install a compiler, you have to specify a download link for the according installation file.\n"
471
  printf "For this project, the GNU Arm Embedded Toolchain is recommended:\n"
472
  printf "  https://developer.arm.com/tools-and-software/open-source-software/developer-tools/gnu-toolchain/gnu-rm\n"
473
  printf "The following link can be used to install the GNU Arm Embedded Toolchain version 8-2018-q4-major:\n"
474
  printf "  https://developer.arm.com/-/media/Files/downloads/gnu-rm/8-2018q4/gcc-arm-none-eabi-8-2018-q4-major-linux.tar.bz2\n"
475
  printf "\n"
476 0a42f078 Thomas Schöpping
  printLog "read installation url from user\n"
477
  local armgcc_downloadurl=""
478 316a2b34 Thomas Schöpping
  while [ -z "$armgcc_downloadurl" ]; do
479 0a42f078 Thomas Schöpping
    read -p "Download link for the installation file: " -e armgcc_downloadurl
480 316a2b34 Thomas Schöpping
    if [ -z "$armgcc_downloadurl" ]; then
481
      printWarning "installation aborted by user\n"
482
      return 1
483
    fi
484 2880bac8 Thomas Schöpping
    # check whether url is valid
485
    wget --spider -r "$armgcc_downloadurl" &>/dev/null
486
    if [ $? -ne 0 ]; then
487
      printError "'$armgcc_downloadurl' can not be reached\n"
488
      return -1
489 0a42f078 Thomas Schöpping
    fi
490
  done
491
  printLog "user selected $armgcc_downloadurl\n"
492
493
  # if the file already exists, ask the user if it should be downloaded again
494 2880bac8 Thomas Schöpping
  local armgcc_tarball=$(basename $(wget --spider -r "$armgcc_downloadurl" 2>&1 | \
495
                                    grep "^--" | \
496
                                    tail -n 1 | \
497
                                    awk '{print $NF}'))
498
  if [ -f "$armgcc_tarball" ]; then
499 0a42f078 Thomas Schöpping
    printWarning "$armgcc_tarball already exists. Delete and redownload? [y/n]\n"
500
    local userinput=""
501
    readUserInput "YyNn" userinput
502
    case "$userinput" in
503
      Y|y)
504
        rm "$armgcc_tarball"
505 2880bac8 Thomas Schöpping
        wget "$armgcc_downloadurl" -O "$armgcc_tarball" | tee -a $LOG_FILE
506 0a42f078 Thomas Schöpping
        ;;
507
      N|n)
508
        ;;
509
      *) # sanity check (exit with error)
510
        printError "unexpected argument: $userinput\n";;
511
    esac
512
  else
513 2880bac8 Thomas Schöpping
    wget "$armgcc_downloadurl" -O "$armgcc_tarball" | tee -a $LOG_FILE
514 0a42f078 Thomas Schöpping
  fi
515
516
  # extract tarball
517
  printInfo "extracting ${armgcc_tarball}...\n"
518
  tar -jxf "$armgcc_tarball" | tee -a $LOG_FILE
519
  local compilerdir=`tar --bzip2 -tf ${armgcc_tarball} | sed -e 's@/.*@@' | uniq`
520
521 72294488 Thomas Schöpping
  # install gcc arm embedded
522 0a42f078 Thomas Schöpping
  printLog "read installation directory from user\n"
523
  local installdir=""
524
  read -p "Installation directory: " -i ${installbasedir}/${compilerdir} -e installdir
525
  printLog "user selected $installdir\n"
526 dab959cd Thomas Schöpping
  linkdir=$(dirname ${installdir})
527 0a42f078 Thomas Schöpping
  printLog "read link directory\n"
528
  read -p "Link directory: " -i $linkdir -e linkdir
529
  printLog "user selected $linkdir\n"
530
  # if the installation path already exists, ask user to overwrite
531
  if [ -d "$installdir" ]; then
532
    printWarning "$installdir already exists. Overwrite? [y/n]\n"
533
    local userinput=""
534
    readUserInput "YyNn" userinput
535
    case "$userinput" in
536
      Y|y)
537
        ;;
538
      N|n)
539
        printWarning "installation aborted by user\n"
540
        return 1
541
        ;;
542
      *) # sanity check (exit with error)
543
        printError "invalid option: $userinput\n";;
544
    esac
545
  # make sure the whole ínstallation path exists
546
  else
547
    while [ ! -d $(dirname "$installdir") ]; do
548
      local dir=$(dirname "$installdir") 
549
      while [ ! -d $(dirname "$dir") ]; do
550
        dir=$(dirname "$dir")
551
      done
552
      echo "mkdir $dir"
553
      mkdir "$dir"
554
    done
555
  fi
556
  # copy the extracted compiler folder
557
  cp -fR "$compilerdir" "$installdir"
558
  # make sure whole link path exists
559
  while [ ! -d "$linkdir" ]; do
560
    local dir="$linkdir"
561
    while [ ! -d $(dirname "$linkdir") ]; do
562
      dir=$(dirname "$dir")
563
    done
564
    mkdir "$dir"
565
  done
566
  # create / overwrite links
567 56360b33 Thomas Schöpping
  local linkpath=$(realpath --relative-base=$linkdir ${installdir}/bin/)
568
  ls ${installdir}/bin/ | xargs -i ln -sf ${linkpath}/{} ${linkdir}/{}
569 0a42f078 Thomas Schöpping
  printInfo "default version set to $(arm-none-eabi-gcc -dumpversion)\n"
570
571
  # append the link directory to the PATH environment variable if required
572
  if [[ ! "$linkdir" = *"$PATH"* ]]; then
573
    local bashrc_file=${HOME}/.bashrc
574
    local bashrc_identifier="##### AMiRo ENVIRONMENT CONFIGURATION #####"
575
    local bashrc_note="# DO NOT EDIT THESE LINES MANUALLY!"
576
    local bashrc_entry="export PATH=\$PATH:$linkdir"
577
578
    # find and edit old entry, or append a new one to the file
579
    local bashrc_idlines=$(grep -x -n "$bashrc_identifier" "$bashrc_file" | cut -f1 -d:) # string of line numbers
580
    bashrc_idlines=(${bashrc_idlines//"\n"/" "}) # array of line numbers
581
    case ${#bashrc_idlines[@]} in
582
583
      # append a new entry to the BASHRC_FILE
584
      0)
585
        # make sure the last line is empty
586
        if [[ ! $(tail -1 $bashrc_file) =~ ^[\ \t]*$ ]]; then
587
          printf "\n" >> $bashrc_file
588
        fi
589
        # append text to file
590
        sed -i '$a'"$bashrc_identifier\n$bashrc_note\n$bashrc_entry\n$bashrc_identifier\n" $bashrc_file
591
        # print note
592
        printInfo "Your $bashrc_file has been updated. You need to source it to apply the changes in your environment.\n"
593
        read -p "  Understood!"
594
        ;;
595
596
      # extend the old entry
597
      2)
598
        # don't do anything if the line is already present
599
        local bashrc_entrylines=$(grep -x -n "$bashrc_entry" $bashrc_file | cut -f1 -d:) # string of line numbers
600
        bashrc_entrylines=(${bashrc_entrylines//"\n"/" "}) # array of line numbers
601
        if [[ ${#bashrc_entrylines[@]} = 0 ]]; then
602
          # insert the entry before the closing identifier
603
          sed -i "${bashrc_idlines[1]}"'i'"$bashrc_entry" $bashrc_file
604
          # print note
605
          printInfo "Your $bashrc_file has been updated. You need to source it to apply the changes in your environment.\n"
606
          read -p "  Understood!"
607
        elif [[ ${#bashrc_entrylines[@]} -eq 1 && ( ${bashrc_entrylines[0]} -lt ${bashrc_idlines[0]} || ${bashrc_entrylines[0]} -gt ${bashrc_idlines[1]} ) ]]; then
608
          # print an error that there is an entry at the wrong place
609
          printError "corrupted entry in your $bashrc_file detected\n"
610
          printf "The following entry was found at the wrong place:\n"
611
          printf "\n"
612
          printf "$bashrc_entry\n"
613
          printf "\n"
614
          printf "To fix this, delete the line and rerun this setup.\n"
615
          read -p "  Understood!"
616
        elif [[ ${#bashrc_entrylines[@]} -gt 1 ]]; then
617
          # print an error that there are multiple entries
618
          printError "corrupted entry in your $bashrc_file detected\n"
619
          printf "There are multiple identical entries in your $bashrc_file file.\n"
620
          printf "To fix it, make sure that it contains the following line exactly once:\n"
621
          printf "\n"
622
          printf "$bashrc_entry\n"
623
          printf "\n"
624
          read -p "  Understood!"
625
        fi
626
        ;;
627
628
      # error state (corrupted entry detected)
629
      *)
630
        printError "unable to append link directory to \$PATH variable\n"
631
        printf "There seems to be a broken entry in your $bashrc_file file.\n"
632
        printf "To fix it, make sure that the following line appears exactly twice and encloses your AMiRo related settings:\n"
633
        printf "\n"
634
        printf "$bashrc_identifier\n"
635
        printf "\n"
636
        read -p "  Understood!"
637
        ;;
638
    esac
639
  fi
640
641
  # clean up the current directory
642
  rm "$armgcc_tarball"
643
  rm -rf "$compilerdir"
644
645
  return 0
646
}
647
648 316a2b34 Thomas Schöpping
### uninstall a version ########################################################
649
# Select an installed version and uninstall it from the system.
650
#
651
# usage:      uninstallVersion <versions> <current_idx> <linkdir>
652
# arguments:  <version>
653
#                 Array of available versions (full path to binary).
654
#             <current_idx>
655
#                 Index of the currently selected version in the array.
656
#             <linkdir>
657
#                 Path where to delete old links.
658
# return:     0
659
#                 No error or warning occurred.
660
#             1
661
#                 Warning: Installation aborted by user.
662
#             -1
663
#                 Error: An exception occurred.
664
#
665
function uninstallVersion {
666
  local versions=("${!1}")
667
  local current_idx="$2"
668
  local linkdir="$3"
669
670
  # check whether at least two installations were detected
671
  if [ ${#versions[@]} -eq 0 ]; then
672
    printError "no installation detected\n"
673
    return -1
674
  else
675
    # print all available versions
676
    printInfo "choose the installation to uninstall to or type 'A' to abort:\n"
677
    for (( cnt=0; cnt<${#versions[@]}; ++cnt )); do
678
      if [ $cnt -eq $current_idx ]; then
679
        printf "*%3u: %s\n" $(($cnt + 1)) ${versions[$cnt]}
680
      else
681
        printf " %3u: %s\n" $(($cnt + 1)) ${versions[$cnt]}
682
      fi
683
    done
684
685
    # read user selection
686
    printLog "read user slection\n"
687
    local userinput=""
688
    while [ -z $userinput ] ; do
689
      read -p "your selection: " -e userinput
690
      printLog "user selection: $userinput\n"
691
      if [[ ! "$userinput" =~ ^[0-9]+$ ]] || [ ! "$userinput" -gt 0 ] || [ ! "$userinput" -le ${#versions[@]} ] && [[ ! "$userinput" =~ ^[Aa]$ ]]; then
692
        printWarning "Please enter an integer between 1 and ${#versions[@]} or 'A' to abort.\n"
693
        userinput=""
694
      fi
695
      if [ ${#versions[@]} -gt 1 ] && [ $((userinput - 1)) -eq $current_idx ]; then
696
        printWarning "Unable to uninstall currently selected version (as long as there are others).\n"
697
        userinput=""
698
      fi
699
    done
700
701
    if [[ "$userinput" =~ ^[Aa]$ ]]; then
702
      printWarning "aborted by user\n"
703
      return 1
704
    else
705
      local idx=$((userinput - 1))
706
      printf "\n"
707
      # prompt selected and aks user for confirmation
708
      printInfo "${versions[$idx]} will be removed. Continue? [y/n]\n"
709
      readUserInput "YyNn" userinput
710
      case "$userinput" in
711
        Y|y)
712
          ;;
713
        N|n)
714
          printWarning "uninstallation process aborted by user\n"
715
          return 1
716
          ;;
717
        *) # sanity check (exit with error)
718
          printError "invalid option: $userinput\n"
719
          return -1
720
          ;;
721
      esac
722
      # find and delete any links pointing to the version to be deleted
723
      for link in `find $linkdir -maxdepth 1 -type l`; do
724
        local l=$link
725
        # follow the link to the actual binary
726
        while [ -L $l ]; do
727
          # differentiate between relative and absolute paths
728
          if [[ $(readlink $l) = /* ]]; then
729
            l=$(readlink $l)
730
          else
731
            l=$(realpath $(dirname $l)/$(readlink $l))
732
          fi
733
        done
734
        # delete the link if it points to the version to be uninstalled
735
        if [ $(dirname $l) == $(dirname ${versions[$idx]}) ]; then
736
          rm $link
737
        fi
738
      done
739
      # delete the version directory (assumed to be one directory up)
740
      rm -rf $(realpath $(dirname ${versions[$idx]})/..)
741
      printInfo "${versions[$idx]} has been removed.\n"
742
    fi
743
  fi
744
745
  return 0
746
}
747
748 0a42f078 Thomas Schöpping
### change default version #####################################################
749
# Change the default arm-none-eabi-gcc version.
750
#
751 316a2b34 Thomas Schöpping
# usage:      changeDefaultVersion <versions> <linkdir>
752 0a42f078 Thomas Schöpping
# argumenst:  <versions>
753
#                 Array of available versions (full path to binary).
754
#             <linkdir>
755
#                 Path where to delete old and create new links.
756
# return:     0
757
#                 No error or warnign occurred.
758
#             -1
759
#                 Error: no installation detected.
760
#
761
function changeDefaultVersion {
762
  local versions=("${!1}")
763
  local linkdir="$2"
764
765
  # check whether an installation was detected
766
  if [ ${#versions[@]} -eq 0 ]; then
767
    printError "no installation detected\n"
768
    return -1
769
  else
770
    # print all available versions
771
    printInfo "choose the installation to switch to or type 'A' to abort:\n"
772
    for (( cnt=0; cnt<${#versions[@]}; ++cnt )); do
773
      printf "  %2u: %s\n" $(($cnt + 1)) ${versions[$cnt]}
774
    done
775
776
    # read user selection
777
    printLog "read user slection\n"
778
    local userinput=""
779
    while [[ ! "$userinput" =~ ^[0-9]+$ ]] || [ ! "$userinput" -gt 0 ] || [ ! "$userinput" -le ${#versions[@]} ] && [[ ! "$userinput" =~ ^[Aa]$ ]]; do
780
      read -p "your selection: " -e userinput
781
      printLog "user selection: $userinput\n"
782
      if [[ ! "$userinput" =~ ^[0-9]+$ ]] || [ ! "$userinput" -gt 0 ] || [ ! "$userinput" -le ${#versions[@]} ] && [[ ! "$userinput" =~ ^[Aa]$ ]]; then
783
        printWarning "Please enter an integer between 1 and ${#versions[@]} or 'A' to abort.\n"
784
      fi
785
    done
786
787
    if [[ "$userinput" =~ ^[Aa]$ ]]; then
788
      printWarning "aborted by user\n"
789
    else
790
      local idx=$((userinput - 1))
791
      # find and delete old links
792
      rm `find $linkdir -maxdepth 1 -type l | grep -Ev "*[0-9]\.[0-9]\.[0-9]"`
793 56360b33 Thomas Schöpping
      # create new links with relative or absolute paths
794 0a42f078 Thomas Schöpping
      local bindir=$(dirname ${versions[$idx]})
795 56360b33 Thomas Schöpping
      local linkpath=$(realpath --relative-base=$linkdir $bindir)
796
      ls $bindir | xargs -i ln -sf $linkpath/{} $linkdir/{}
797 0a42f078 Thomas Schöpping
      printInfo "default version set to $(arm-none-eabi-gcc -dumpversion)\n"
798
    fi
799
  fi
800
801
  return 0
802
}
803
804
### main function of this script ###############################################
805
# The IDE setup lets the user select an IDE of choice.
806
# As of now, only QtCreator is supported.
807
#
808
# usage:      see function printHelp
809
# arguments:  see function printHelp
810
# return:     0
811
#                 No error or warning occurred.
812
#
813
function main {
814
  # print welcome/info text if not suppressed
815
  if [[ $@ != *"--noinfo"* ]]; then
816
    printWelcomeText
817
  else
818
    printf "######################################################################\n"
819
  fi
820
  printf "\n"
821
822 1446566f Thomas Schöpping
  # if --help or -h was specified, print the help text and exit
823
  if [[ $@ == *"--help"* || $@ == *"-h"* ]]; then
824
    printHelp
825
    printf "\n"
826
    quitScript
827
  fi
828
829 0a42f078 Thomas Schöpping
  # set log file if specified
830
  if [[ $@ == *"--log"* ]] || [[ $@ == *"--LOG"* ]]; then
831
    # get the parameter (file name)
832
    local cmdidx=1
833
    while [[ ! "${!cmdidx}" = "--log"* ]] && [[ ! "${!cmdidx}" = "--LOG"* ]]; do
834
      cmdidx=$[cmdidx + 1]
835
    done
836
    local cmd="${!cmdidx}"
837
    local logfile=""
838
    if [[ "$cmd" = "--log="* ]] || [[ "$cmd" = "--LOG="* ]]; then
839
      logfile=${cmd#*=}
840
    else
841
      local filenameidx=$((cmdidx + 1))
842
      logfile="${!filenameidx}"
843
    fi
844
    # optionally force silent appending
845
    if [[ "$cmd" = "--LOG"* ]]; then
846 0dc9f2f9 Thomas Schöpping
      setLogFile --option=c --quiet "$logfile" LOG_FILE
847 0a42f078 Thomas Schöpping
    else
848
      setLogFile "$logfile" LOG_FILE
849
      printf "\n"
850
    fi
851
  fi
852
  # log script name
853
  printLog "this is $(realpath ${BASH_SOURCE[0]})\n"
854
855
  # detect installed versions and inform user
856
  local installedversions=()
857
  local currentversion=""
858 316a2b34 Thomas Schöpping
  local currentversionidx="n/a"
859
  detectInstalledVersions installedversions currentversion currentversionidx
860 0a42f078 Thomas Schöpping
  case "${#installedversions[@]}" in
861
    0)
862
      printInfo "no installation has been detected\n";;
863
    1)
864
      printInfo "1 installation has been detected:\n";;
865
    *)
866
      printInfo "${#installedversions[@]} installations have been detected:\n";;
867
  esac
868
  for (( idx=0; idx<${#installedversions[@]}; ++idx )); do
869
    if [ ${installedversions[$idx]} = "$currentversion" ]; then
870
      printInfo "  * ${installedversions[$idx]}\n"
871
    else
872
      printInfo "    ${installedversions[$idx]}\n"
873
    fi
874
  done
875
  printf "\n"
876
877
  # parse arguments
878
  local otherargs=()
879
  while [ $# -gt 0 ]; do
880
    if ( parseIsOption $1 ); then
881
      case "$1" in
882
        -h|--help) # already handled; ignore
883
          shift 1;;
884 316a2b34 Thomas Schöpping
        -i|--install)
885 0a42f078 Thomas Schöpping
          if [ -z "$currentversion" ]; then
886
            installNewVersion
887
          else
888 316a2b34 Thomas Schöpping
            installNewVersion --install=$(realpath $(dirname $currentversion)/../..) --link=$(realpath $(dirname $currentversion)/../..)
889
          fi
890
          detectInstalledVersions installedversions currentversion currentversionidx
891
          printf "\n"; shift 1;;
892
        -u|--uninstall)
893
          if [ ! -z "$currentversion" ]; then
894
            uninstallVersion installedversions[@] $currentversionidx $(realpath $(dirname $currentversion)/../..)
895
            detectInstalledVersions installedversions currentversion currentversionidx
896
          else
897
            printError "no installation detected\n"
898 0a42f078 Thomas Schöpping
          fi
899
          printf "\n"; shift 1;;
900
        -c|--change)
901 316a2b34 Thomas Schöpping
          if [ ! -z "$currentversion" ]; then
902
            changeDefaultVersion installedversions[@] $(realpath $(dirname $currentversion)/../..)
903
          else
904
            printError "no installation detected\n"
905
          fi
906
          printf "\n"; shift 1;;
907 0a42f078 Thomas Schöpping
        -q|--quit)
908
          quitScript; shift 1;;
909
        --log=*|--LOG=*) # already handled; ignore
910
          shift 1;;
911
        --log|--LOG) # already handled; ignore
912
          shift 2;;
913
        --noinfo) # already handled; ignore
914
          shift 1;;
915
        *)
916
          printError "invalid option: $1\n"; shift 1;;
917
      esac
918
    else
919
      otherargs+=("$1")
920
      shift 1
921
    fi
922
  done
923
924
  # interactive menu
925
  while ( true ); do
926
    # main menu info prompt and selection
927
    printInfo "GCC setup main menu\n"
928
    printf "Please select one of the following actions:\n"
929
    printf "  [I] - install another version\n"
930 316a2b34 Thomas Schöpping
    printf "  [U] - uninstall a version\n"
931 0a42f078 Thomas Schöpping
    printf "  [C] - change default version\n"
932
    printf "  [Q] - quit this setup\n"
933
    local userinput=""
934 316a2b34 Thomas Schöpping
    readUserInput "IiUuCcQq" userinput
935 0a42f078 Thomas Schöpping
    printf "\n"
936
937
    # evaluate user selection
938
    case "$userinput" in
939
      I|i)
940
        if [ -z "$currentversion" ]; then
941
          installNewVersion
942
        else
943 316a2b34 Thomas Schöpping
          installNewVersion --install=$(realpath $(dirname $currentversion)/../..) --link=$(realpath $(dirname $currentversion)/../..)
944
        fi
945
        detectInstalledVersions installedversions currentversion currentversionidx
946
        printf "\n";;
947
      U|u)
948
        if [ ! -z "$currentversion" ]; then
949
          uninstallVersion installedversions[@] $currentversionidx $(realpath $(dirname $currentversion)/../..)
950
          detectInstalledVersions installedversions currentversion currentversionidx
951
        else
952
          printError "no installation detected\n"
953 0a42f078 Thomas Schöpping
        fi
954
        printf "\n";;
955
      C|c)
956 316a2b34 Thomas Schöpping
        if [ ! -z "$currentversion" ]; then
957
          changeDefaultVersion installedversions[@] $(realpath $(dirname $currentversion)/../..)
958
        else
959
          printError "no installation detected\n"
960
        fi
961
        printf "\n";;
962 0a42f078 Thomas Schöpping
      Q|q)
963
        quitScript;;
964
      *) # sanity check (exit with error)
965
        printError "unexpected argument: $userinput\n";;
966
    esac
967
  done
968
969
  exit 0
970
}
971
972
################################################################################
973
# SCRIPT ENTRY POINT                                                           #
974
################################################################################
975
976
main "$@"