Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (33.715 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
#
432
function installNewVersion {
433
  local installbasedir=${HOME}/gcc-arm-embedded
434
  local linkdir="/usr/bin"
435

    
436
  # parse arguments
437
  local otherargs=()
438
  while [ $# -gt 0 ]; do
439
    if ( parseIsOption $1 ); then
440
      case "$1" in
441
        -i=*|--install=*)
442
          installbasedir=$(realpath "${1#*=}"); shift 1;;
443
        -i|--install)
444
          installbasedir="$2"; shift 2;;
445
        -l=*|--link=*)
446
          linkdir=$(realpath "${1#*=}"); shift 1;;
447
        -l|--link)
448
          linkdir="$2"; shift 2;;
449
        *) # sanity check (exit with error)
450
          printError "invalid option: $1\n"; shift 1;;
451
      esac
452
    else
453
      otherargs+=("$1")
454
      shift 1
455
    fi
456
  done
457

    
458
  # read download URL form user
459
  printLog "read installation url from user\n"
460
  local armgcc_downloadurl=""
461
  while [ -z "$armgcc_downloadurl" ]; do
462
    read -p "Download link for the installation file: " -e armgcc_downloadurl
463
    if [ -z "$armgcc_downloadurl" ]; then
464
      printWarning "installation aborted by user\n"
465
      return 1
466
    fi
467
    if [[ $armgcc_downloadurl != *".tar.bz2" ]]; then
468
      printWarning "please specify a .tar.bz2 file\n"
469
      armgcc_downloadurl=""
470
    fi
471
    if [ ! wget --spider $armgcc_downloadurl 2>/dev/null ]; then
472
      printWarning "$armgcc_downloadurl can not be reached\n"
473
      armgcc_downloadurl=""
474
    fi
475
  done
476
  printLog "user selected $armgcc_downloadurl\n"
477

    
478
  # if the file already exists, ask the user if it should be downloaded again
479
  local armgcc_tarball=$(basename "$armgcc_downloadurl")
480
  if [ -e "$armgcc_tarball" ]; then
481
    printWarning "$armgcc_tarball already exists. Delete and redownload? [y/n]\n"
482
    local userinput=""
483
    readUserInput "YyNn" userinput
484
    case "$userinput" in
485
      Y|y)
486
        rm "$armgcc_tarball"
487
        wget "$armgcc_downloadurl" | tee -a $LOG_FILE
488
        ;;
489
      N|n)
490
        ;;
491
      *) # sanity check (exit with error)
492
        printError "unexpected argument: $userinput\n";;
493
    esac
494
  else
495
    wget "$armgcc_downloadurl" | tee -a $LOG_FILE
496
  fi
497

    
498
  # extract tarball
499
  printInfo "extracting ${armgcc_tarball}...\n"
500
  tar -jxf "$armgcc_tarball" | tee -a $LOG_FILE
501
  local compilerdir=`tar --bzip2 -tf ${armgcc_tarball} | sed -e 's@/.*@@' | uniq`
502

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

    
553
  # append the link directory to the PATH environment variable if required
554
  if [[ ! "$linkdir" = *"$PATH"* ]]; then
555
    local bashrc_file=${HOME}/.bashrc
556
    local bashrc_identifier="##### AMiRo ENVIRONMENT CONFIGURATION #####"
557
    local bashrc_note="# DO NOT EDIT THESE LINES MANUALLY!"
558
    local bashrc_entry="export PATH=\$PATH:$linkdir"
559

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

    
565
      # append a new entry to the BASHRC_FILE
566
      0)
567
        # make sure the last line is empty
568
        if [[ ! $(tail -1 $bashrc_file) =~ ^[\ \t]*$ ]]; then
569
          printf "\n" >> $bashrc_file
570
        fi
571
        # append text to file
572
        sed -i '$a'"$bashrc_identifier\n$bashrc_note\n$bashrc_entry\n$bashrc_identifier\n" $bashrc_file
573
        # print note
574
        printInfo "Your $bashrc_file has been updated. You need to source it to apply the changes in your environment.\n"
575
        read -p "  Understood!"
576
        ;;
577

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

    
610
      # error state (corrupted entry detected)
611
      *)
612
        printError "unable to append link directory to \$PATH variable\n"
613
        printf "There seems to be a broken entry in your $bashrc_file file.\n"
614
        printf "To fix it, make sure that the following line appears exactly twice and encloses your AMiRo related settings:\n"
615
        printf "\n"
616
        printf "$bashrc_identifier\n"
617
        printf "\n"
618
        read -p "  Understood!"
619
        ;;
620
    esac
621
  fi
622

    
623
  # clean up the current directory
624
  rm "$armgcc_tarball"
625
  rm -rf "$compilerdir"
626

    
627
  return 0
628
}
629

    
630
### uninstall a version ########################################################
631
# Select an installed version and uninstall it from the system.
632
#
633
# usage:      uninstallVersion <versions> <current_idx> <linkdir>
634
# arguments:  <version>
635
#                 Array of available versions (full path to binary).
636
#             <current_idx>
637
#                 Index of the currently selected version in the array.
638
#             <linkdir>
639
#                 Path where to delete old links.
640
# return:     0
641
#                 No error or warning occurred.
642
#             1
643
#                 Warning: Installation aborted by user.
644
#             -1
645
#                 Error: An exception occurred.
646
#
647
function uninstallVersion {
648
  local versions=("${!1}")
649
  local current_idx="$2"
650
  local linkdir="$3"
651

    
652
  # check whether at least two installations were detected
653
  if [ ${#versions[@]} -eq 0 ]; then
654
    printError "no installation detected\n"
655
    return -1
656
  else
657
    # print all available versions
658
    printInfo "choose the installation to uninstall to or type 'A' to abort:\n"
659
    for (( cnt=0; cnt<${#versions[@]}; ++cnt )); do
660
      if [ $cnt -eq $current_idx ]; then
661
        printf "*%3u: %s\n" $(($cnt + 1)) ${versions[$cnt]}
662
      else
663
        printf " %3u: %s\n" $(($cnt + 1)) ${versions[$cnt]}
664
      fi
665
    done
666

    
667
    # read user selection
668
    printLog "read user slection\n"
669
    local userinput=""
670
    while [ -z $userinput ] ; do
671
      read -p "your selection: " -e userinput
672
      printLog "user selection: $userinput\n"
673
      if [[ ! "$userinput" =~ ^[0-9]+$ ]] || [ ! "$userinput" -gt 0 ] || [ ! "$userinput" -le ${#versions[@]} ] && [[ ! "$userinput" =~ ^[Aa]$ ]]; then
674
        printWarning "Please enter an integer between 1 and ${#versions[@]} or 'A' to abort.\n"
675
        userinput=""
676
      fi
677
      if [ ${#versions[@]} -gt 1 ] && [ $((userinput - 1)) -eq $current_idx ]; then
678
        printWarning "Unable to uninstall currently selected version (as long as there are others).\n"
679
        userinput=""
680
      fi
681
    done
682

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

    
727
  return 0
728
}
729

    
730
### change default version #####################################################
731
# Change the default arm-none-eabi-gcc version.
732
#
733
# usage:      changeDefaultVersion <versions> <linkdir>
734
# argumenst:  <versions>
735
#                 Array of available versions (full path to binary).
736
#             <linkdir>
737
#                 Path where to delete old and create new links.
738
# return:     0
739
#                 No error or warnign occurred.
740
#             -1
741
#                 Error: no installation detected.
742
#
743
function changeDefaultVersion {
744
  local versions=("${!1}")
745
  local linkdir="$2"
746

    
747
  # check whether an installation was detected
748
  if [ ${#versions[@]} -eq 0 ]; then
749
    printError "no installation detected\n"
750
    return -1
751
  else
752
    # print all available versions
753
    printInfo "choose the installation to switch to or type 'A' to abort:\n"
754
    for (( cnt=0; cnt<${#versions[@]}; ++cnt )); do
755
      printf "  %2u: %s\n" $(($cnt + 1)) ${versions[$cnt]}
756
    done
757

    
758
    # read user selection
759
    printLog "read user slection\n"
760
    local userinput=""
761
    while [[ ! "$userinput" =~ ^[0-9]+$ ]] || [ ! "$userinput" -gt 0 ] || [ ! "$userinput" -le ${#versions[@]} ] && [[ ! "$userinput" =~ ^[Aa]$ ]]; do
762
      read -p "your selection: " -e userinput
763
      printLog "user selection: $userinput\n"
764
      if [[ ! "$userinput" =~ ^[0-9]+$ ]] || [ ! "$userinput" -gt 0 ] || [ ! "$userinput" -le ${#versions[@]} ] && [[ ! "$userinput" =~ ^[Aa]$ ]]; then
765
        printWarning "Please enter an integer between 1 and ${#versions[@]} or 'A' to abort.\n"
766
      fi
767
    done
768

    
769
    if [[ "$userinput" =~ ^[Aa]$ ]]; then
770
      printWarning "aborted by user\n"
771
    else
772
      local idx=$((userinput - 1))
773
      # find and delete old links
774
      rm `find $linkdir -maxdepth 1 -type l | grep -Ev "*[0-9]\.[0-9]\.[0-9]"`
775
      # create new links with relative or absolute paths
776
      local bindir=$(dirname ${versions[$idx]})
777
      local linkpath=$(realpath --relative-base=$linkdir $bindir)
778
      ls $bindir | xargs -i ln -sf $linkpath/{} $linkdir/{}
779
      printInfo "default version set to $(arm-none-eabi-gcc -dumpversion)\n"
780
    fi
781
  fi
782

    
783
  return 0
784
}
785

    
786
### main function of this script ###############################################
787
# The IDE setup lets the user select an IDE of choice.
788
# As of now, only QtCreator is supported.
789
#
790
# usage:      see function printHelp
791
# arguments:  see function printHelp
792
# return:     0
793
#                 No error or warning occurred.
794
#
795
function main {
796
  # print welcome/info text if not suppressed
797
  if [[ $@ != *"--noinfo"* ]]; then
798
    printWelcomeText
799
  else
800
    printf "######################################################################\n"
801
  fi
802
  printf "\n"
803

    
804
  # if --help or -h was specified, print the help text and exit
805
  if [[ $@ == *"--help"* || $@ == *"-h"* ]]; then
806
    printHelp
807
    printf "\n"
808
    quitScript
809
  fi
810

    
811
  # set log file if specified
812
  if [[ $@ == *"--log"* ]] || [[ $@ == *"--LOG"* ]]; then
813
    # get the parameter (file name)
814
    local cmdidx=1
815
    while [[ ! "${!cmdidx}" = "--log"* ]] && [[ ! "${!cmdidx}" = "--LOG"* ]]; do
816
      cmdidx=$[cmdidx + 1]
817
    done
818
    local cmd="${!cmdidx}"
819
    local logfile=""
820
    if [[ "$cmd" = "--log="* ]] || [[ "$cmd" = "--LOG="* ]]; then
821
      logfile=${cmd#*=}
822
    else
823
      local filenameidx=$((cmdidx + 1))
824
      logfile="${!filenameidx}"
825
    fi
826
    # optionally force silent appending
827
    if [[ "$cmd" = "--LOG"* ]]; then
828
      setLogFile --option=c --quiet "$logfile" LOG_FILE
829
    else
830
      setLogFile "$logfile" LOG_FILE
831
      printf "\n"
832
    fi
833
  fi
834
  # log script name
835
  printLog "this is $(realpath ${BASH_SOURCE[0]})\n"
836

    
837
  # detect installed versions and inform user
838
  local installedversions=()
839
  local currentversion=""
840
  local currentversionidx="n/a"
841
  detectInstalledVersions installedversions currentversion currentversionidx
842
  case "${#installedversions[@]}" in
843
    0)
844
      printInfo "no installation has been detected\n";;
845
    1)
846
      printInfo "1 installation has been detected:\n";;
847
    *)
848
      printInfo "${#installedversions[@]} installations have been detected:\n";;
849
  esac
850
  for (( idx=0; idx<${#installedversions[@]}; ++idx )); do
851
    if [ ${installedversions[$idx]} = "$currentversion" ]; then
852
      printInfo "  * ${installedversions[$idx]}\n"
853
    else
854
      printInfo "    ${installedversions[$idx]}\n"
855
    fi
856
  done
857
  printf "\n"
858

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

    
906
  # interactive menu
907
  while ( true ); do
908
    # main menu info prompt and selection
909
    printInfo "GCC setup main menu\n"
910
    printf "Please select one of the following actions:\n"
911
    printf "  [I] - install another version\n"
912
    printf "  [U] - uninstall a version\n"
913
    printf "  [C] - change default version\n"
914
    printf "  [Q] - quit this setup\n"
915
    local userinput=""
916
    readUserInput "IiUuCcQq" userinput
917
    printf "\n"
918

    
919
    # evaluate user selection
920
    case "$userinput" in
921
      I|i)
922
        if [ -z "$currentversion" ]; then
923
          installNewVersion
924
        else
925
          installNewVersion --install=$(realpath $(dirname $currentversion)/../..) --link=$(realpath $(dirname $currentversion)/../..)
926
        fi
927
        detectInstalledVersions installedversions currentversion currentversionidx
928
        printf "\n";;
929
      U|u)
930
        if [ ! -z "$currentversion" ]; then
931
          uninstallVersion installedversions[@] $currentversionidx $(realpath $(dirname $currentversion)/../..)
932
          detectInstalledVersions installedversions currentversion currentversionidx
933
        else
934
          printError "no installation detected\n"
935
        fi
936
        printf "\n";;
937
      C|c)
938
        if [ ! -z "$currentversion" ]; then
939
          changeDefaultVersion installedversions[@] $(realpath $(dirname $currentversion)/../..)
940
        else
941
          printError "no installation detected\n"
942
        fi
943
        printf "\n";;
944
      Q|q)
945
        quitScript;;
946
      *) # sanity check (exit with error)
947
        printError "unexpected argument: $userinput\n";;
948
    esac
949
  done
950

    
951
  exit 0
952
}
953

    
954
################################################################################
955
# SCRIPT ENTRY POINT                                                           #
956
################################################################################
957

    
958
main "$@"