Statistics
| Branch: | Tag: | Revision:

amiro-blt / compiler / GCC / gccsetup.sh @ 1446566f

History | View | Annotate | Download (27 KB)

1
################################################################################
2
# AMiRo-BLT is an bootloader and toolchain designed for the Autonomous Mini    #
3
# Robot (AMiRo) platform.                                                      #
4
# Copyright (C) 2016..2017  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', 'r' and 'n'.
173
#                 - a: append
174
#                 - r: delete and restart
175
#                 - n: no log
176
#                 If no option is secified but <file> exists, an interactive selection is provided.
177
#             --quiet
178
#                 Suppress all messages.
179
#             <infile>
180
#                 Path of the wanted log file.
181
#             <outvar>
182
#                 Variable to store the path of the log file to.
183
# return:     0
184
#                 No error or warning occurred.
185
#             -1
186
#                 Error: invalid input
187
#
188
function setLogFile {
189
  local filepath=""
190
  local option=""
191
  local quiet=false
192

    
193
  # parse arguments
194
  local otherargs=()
195
  while [ $# -gt 0 ]; do
196
    if ( parseIsOption $1 ); then
197
      case "$1" in
198
        -o=*|--option=*)
199
          option=${1#*=}; shift 1;;
200
        -o*|--option*)
201
          option="$2"; shift 2;;
202
        -q|--quiet)
203
          quiet=true; shift 1;;
204
        *)
205
          printError "invalid option: $1\n"; shift 1;;
206
      esac
207
    else
208
      otherargs+=("$1")
209
      shift 1
210
    fi
211
  done
212
  filepath=$(realpath ${otherargs[0]})
213

    
214
  # if file already exists
215
  if [ -e $filepath ]; then
216
    # if no option was specified, ask what to do
217
    if [ -z "$option" ]; then
218
      printWarning "log file $filepath already esists\n"
219
      local userinput=""
220
      printf "Select what to do:\n"
221
      printf "  [A] - append log\n"
222
      printf "  [R] - restart log (delete existing file)\n"
223
      printf "  [N] - no log\n"
224
      readUserInput "AaRrNn" userinput
225
      option=${userinput,,}
226
    fi
227
    # evaluate option
228
    case "$option" in
229
      a)
230
        if [ $quiet = false ]; then
231
          printInfo "appending log to $filepath\n"
232
        fi
233
        printf "\n" >> $filepath
234
        printf "######################################################################\n" >> $filepath
235
        printf "\n" >> $filepath
236
        ;;
237
      r)
238
        echo -n "" > $filepath
239
        if [ $quiet = false ]; then
240
          printInfo "content of $filepath wiped\n"
241
        fi
242
        ;;
243
      n)
244
        if [ $quiet = false ]; then
245
          printInfo "no log file will be generated\n"
246
        fi
247
        filepath=""
248
        ;;
249
      *) # sanity check (return error)
250
        printError "unexpected argument: $option\n"; return -1;;
251
    esac
252
  else
253
    if [ $quiet = false ]; then
254
      printInfo "log file set to $filepath\n"
255
    fi
256
  fi
257

    
258
  eval ${otherargs[1]}="$filepath"
259

    
260
  return 0
261
}
262

    
263
################################################################################
264
# SPECIFIC FUNCTIONS                                                           #
265
################################################################################
266

    
267
### print welcome text #########################################################
268
# Prints a welcome message to standard out.
269
#
270
# usage:      printWelcomeText
271
# arguments:  n/a
272
# return:     n/a
273
#
274
function printWelcomeText {
275
  printf "######################################################################\n"
276
  printf "#                                                                    #\n"
277
  printf "#                     Welcome to the GCC setup!                      #\n"
278
  printf "#                                                                    #\n"
279
  printf "######################################################################\n"
280
  printf "#                                                                    #\n"
281
  printf "# Copyright (c) 2016..2017  Thomas Schöpping                         #\n"
282
  printf "#                                                                    #\n"
283
  printf "# This is free software; see the source for copying conditions.      #\n"
284
  printf "# There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR  #\n"
285
  printf "# A PARTICULAR PURPOSE. The development of this software was         #\n"
286
  printf "# supported by the Excellence Cluster EXC 227 Cognitive Interaction  #\n"
287
  printf "# Technology. The Excellence Cluster EXC 227 is a grant of the       #\n"
288
  printf "# Deutsche Forschungsgemeinschaft (DFG) in the context of the German #\n"
289
  printf "# Excellence Initiative.                                             #\n"
290
  printf "#                                                                    #\n"
291
  printf "######################################################################\n"
292
}
293

    
294
### print help #################################################################
295
# Prints a help text to standard out.
296
#
297
# usage:      printHelp
298
# arguments:  n/a
299
# return:     n/a
300
#
301
function printHelp {
302
  printInfo "printing help text\n"
303
  printf "usage:    $(basename ${BASH_SOURCE[0]}) [-h|--help] [-i|--install] [-c|--change] [-q|--quit] [--log=<file>]\n"
304
  printf "\n"
305
  printf "options:  -h, --help\n"
306
  printf "              Print this help text.\n"
307
  printf "          -i, --install\n"
308
  printf "              Install another version.\n"
309
  printf "          -c, --change\n"
310
  printf "              Change the default version.\n"
311
  printf "          -q, --quit\n"
312
  printf "              Quit the script.\n"
313
  printf "          --log=<file>\n"
314
  printf "              Specify a log file.\n"
315
}
316

    
317
### detect installed versions ##################################################
318
# Detect all installed version of arm-none-eabi-gcc, if any.
319
#
320
# usage:      detectInstalledVersions <binarray> <current>
321
# arguments:  <binarray>
322
#                 Array variable to store all detected binary paths to. 
323
#             <current>
324
#                 Variable to store the currently active binary to.
325
# return:     n/a
326
#
327
function detectInstalledVersions {
328
  local armgcc_command=$(command -v arm-none-eabi-gcc)
329
  local armgcc_commanddir=${HOME}/gcc-none-eabi
330
  local armgcc_currentbin=""
331
  local armgcc_installdir=${HOME}/gcc-none-eabi
332
  local armgcc_bins=()
333
  local armgcc_bincnt=0
334

    
335
  # check for already installed versions
336
  if [ -n "$armgcc_command" ]; then
337
    # follow the link to the actual binary
338
    armgcc_commanddir=$(dirname $armgcc_command)
339
    armgcc_currentbin=$armgcc_command
340
    while [ -L $armgcc_currentbin ]; do
341
      armgcc_currentbin=$(readlink $armgcc_currentbin)
342
    done
343
    # the installation location is assumed to be two directories up
344
    armgcc_installdir=$(realpath $(dirname ${armgcc_currentbin})/../../)
345
    # list all detected instalations
346
    for dir in $(ls -d ${armgcc_installdir}/*/); do
347
      if [ -f ${dir}/bin/arm-none-eabi-gcc ]; then
348
        armgcc_bins[$armgcc_bincnt]=${dir}bin/arm-none-eabi-gcc
349
        armgcc_bincnt=$((armgcc_bincnt + 1))
350
      fi
351
    done
352
  fi
353

    
354
  eval "$1=(${armgcc_bins[*]})"
355
  eval $2="$armgcc_currentbin"
356
}
357

    
358
### install new version ########################################################
359
# Fetches an installation package from the internet, installs it and expands
360
# the $PATH environment variable (via .bashrc) if required.
361
#
362
# usage:      installNewVersion [-i|--install=<path>] [-l|--link=<path>]
363
# argumenst:  -i, --install <path>
364
#                 Path where to install the new version to.
365
#             -l, --link <path>
366
#                 Path where to create according links.
367
# return:     0
368
#                 No error or warnign occurred.
369
#             1
370
#                 Warning: Installation aborted by user.
371
#
372
function installNewVersion {
373
  local installbasedir=${HOME}/gcc-arm-embedded
374
  local linkdir="/usr/bin"
375

    
376
  # parse arguments
377
  local otherargs=()
378
  while [ $# -gt 0 ]; do
379
    if ( parseIsOption $1 ); then
380
      case "$1" in
381
        -i=*|--install=*)
382
          installbasedir=$(realpath "${1#*=}"); shift 1;;
383
        -i|--install)
384
          installbasedir="$2"; shift 2;;
385
        -l=*|--link=*)
386
          linkdir=$(realpath "${1#*=}"); shift 1;;
387
        -l|--link)
388
          linkdir="$2"; shift 2;;
389
        *) # sanity check (exit with error)
390
          printError "invalid option: $1\n"; shift 1;;
391
      esac
392
    else
393
      otherargs+=("$1")
394
      shift 1
395
    fi
396
  done
397

    
398
  # read download URL form user
399
  printLog "read installation url from user\n"
400
  local armgcc_downloadurl=""
401
  while [[ "$armgcc_downloadurl" != *".tar.bz2" ]]; do
402
    read -p "Download link for the installation file: " -e armgcc_downloadurl
403
    if [[ $armgcc_downloadurl != *".tar.bz2" ]]; then
404
      printWarning "please specify a .tar.bz2 file\n"
405
    fi
406
  done
407
  printLog "user selected $armgcc_downloadurl\n"
408

    
409
  # if the file already exists, ask the user if it should be downloaded again
410
  local armgcc_tarball=$(basename "$armgcc_downloadurl")
411
  if [ -e "$armgcc_tarball" ]; then
412
    printWarning "$armgcc_tarball already exists. Delete and redownload? [y/n]\n"
413
    local userinput=""
414
    readUserInput "YyNn" userinput
415
    case "$userinput" in
416
      Y|y)
417
        rm "$armgcc_tarball"
418
        wget "$armgcc_downloadurl" | tee -a $LOG_FILE
419
        ;;
420
      N|n)
421
        ;;
422
      *) # sanity check (exit with error)
423
        printError "unexpected argument: $userinput\n";;
424
    esac
425
  else
426
    wget "$armgcc_downloadurl" | tee -a $LOG_FILE
427
  fi
428

    
429
  # extract tarball
430
  printInfo "extracting ${armgcc_tarball}...\n"
431
  tar -jxf "$armgcc_tarball" | tee -a $LOG_FILE
432
  local compilerdir=`tar --bzip2 -tf ${armgcc_tarball} | sed -e 's@/.*@@' | uniq`
433

    
434
  # install gcc arm mebedded
435
  printLog "read installation directory from user\n"
436
  local installdir=""
437
  read -p "Installation directory: " -i ${installbasedir}/${compilerdir} -e installdir
438
  printLog "user selected $installdir\n"
439
  printLog "read link directory\n"
440
  read -p "Link directory: " -i $linkdir -e linkdir
441
  printLog "user selected $linkdir\n"
442
  # if the installation path already exists, ask user to overwrite
443
  if [ -d "$installdir" ]; then
444
    printWarning "$installdir already exists. Overwrite? [y/n]\n"
445
    local userinput=""
446
    readUserInput "YyNn" userinput
447
    case "$userinput" in
448
      Y|y)
449
        ;;
450
      N|n)
451
        printWarning "installation aborted by user\n"
452
        return 1
453
        ;;
454
      *) # sanity check (exit with error)
455
        printError "invalid option: $userinput\n";;
456
    esac
457
  # make sure the whole ínstallation path exists
458
  else
459
    echo "$installdir path not exist"
460
    while [ ! -d $(dirname "$installdir") ]; do
461
      local dir=$(dirname "$installdir") 
462
      while [ ! -d $(dirname "$dir") ]; do
463
        dir=$(dirname "$dir")
464
      done
465
      echo "mkdir $dir"
466
      mkdir "$dir"
467
    done
468
  fi
469
  # copy the extracted compiler folder
470
  cp -fR "$compilerdir" "$installdir"
471
  # make sure whole link path exists
472
  while [ ! -d "$linkdir" ]; do
473
    local dir="$linkdir"
474
    while [ ! -d $(dirname "$linkdir") ]; do
475
      dir=$(dirname "$dir")
476
    done
477
    mkdir "$dir"
478
  done
479
  # create / overwrite links
480
  ls ${installdir}/bin/ | xargs -i ln -sf ${installdir}/bin/{} ${linkdir}/{}
481
  printInfo "default version set to $(arm-none-eabi-gcc -dumpversion)\n"
482

    
483
  read -p "bashrc stuff"
484

    
485
  # append the link directory to the PATH environment variable if required
486
  if [[ ! "$linkdir" = *"$PATH"* ]]; then
487
    local bashrc_file=${HOME}/.bashrc
488
    local bashrc_identifier="##### AMiRo ENVIRONMENT CONFIGURATION #####"
489
    local bashrc_note="# DO NOT EDIT THESE LINES MANUALLY!"
490
    local bashrc_entry="export PATH=\$PATH:$linkdir"
491

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

    
497
      # append a new entry to the BASHRC_FILE
498
      0)
499
        # make sure the last line is empty
500
        if [[ ! $(tail -1 $bashrc_file) =~ ^[\ \t]*$ ]]; then
501
          printf "\n" >> $bashrc_file
502
        fi
503
        # append text to file
504
        sed -i '$a'"$bashrc_identifier\n$bashrc_note\n$bashrc_entry\n$bashrc_identifier\n" $bashrc_file
505
        # print note
506
        printInfo "Your $bashrc_file has been updated. You need to source it to apply the changes in your environment.\n"
507
        read -p "  Understood!"
508
        ;;
509

    
510
      # extend the old entry
511
      2)
512
        # don't do anything if the line is already present
513
        local bashrc_entrylines=$(grep -x -n "$bashrc_entry" $bashrc_file | cut -f1 -d:) # string of line numbers
514
        bashrc_entrylines=(${bashrc_entrylines//"\n"/" "}) # array of line numbers
515
        printf "$bashrc_entrylines\n"
516
        if [[ ${#bashrc_entrylines[@]} = 0 ]]; then
517
          # insert the entry before the closing identifier
518
          sed -i "${bashrc_idlines[1]}"'i'"$bashrc_entry" $bashrc_file
519
          # print note
520
          printInfo "Your $bashrc_file has been updated. You need to source it to apply the changes in your environment.\n"
521
          read -p "  Understood!"
522
        elif [[ ${#bashrc_entrylines[@]} -eq 1 && ( ${bashrc_entrylines[0]} -lt ${bashrc_idlines[0]} || ${bashrc_entrylines[0]} -gt ${bashrc_idlines[1]} ) ]]; then
523
          # print an error that there is an entry at the wrong place
524
          printError "corrupted entry in your $bashrc_file detected\n"
525
          printf "The following entry was found at the wrong place:\n"
526
          printf "\n"
527
          printf "$bashrc_entry\n"
528
          printf "\n"
529
          printf "To fix this, delete the line and rerun this setup.\n"
530
          read -p "  Understood!"
531
        elif [[ ${#bashrc_entrylines[@]} -gt 1 ]]; then
532
          # print an error that there are multiple entries
533
          printError "corrupted entry in your $bashrc_file detected\n"
534
          printf "There are multiple identical entries in your $bashrc_file file.\n"
535
          printf "To fix it, make sure that it contains the following line exactly once:\n"
536
          printf "\n"
537
          printf "$bashrc_entry\n"
538
          printf "\n"
539
          read -p "  Understood!"
540
        fi
541
        ;;
542

    
543
      # error state (corrupted entry detected)
544
      *)
545
        printError "unable to append link directory to \$PATH variable\n"
546
        printf "There seems to be a broken entry in your $bashrc_file file.\n"
547
        printf "To fix it, make sure that the following line appears exactly twice and encloses your AMiRo related settings:\n"
548
        printf "\n"
549
        printf "$bashrc_identifier\n"
550
        printf "\n"
551
        read -p "  Understood!"
552
        ;;
553
    esac
554
  fi
555

    
556
  # clean up the current directory
557
  rm "$armgcc_tarball"
558
  rm -rf "$compilerdir"
559

    
560
  return 0
561
}
562

    
563
### change default version #####################################################
564
# Change the default arm-none-eabi-gcc version.
565
#
566
# usage:      installNewVersion <versions> <linkdir>
567
# argumenst:  <versions>
568
#                 Array of available versions (full path to binary).
569
#             <linkdir>
570
#                 Path where to delete old and create new links.
571
# return:     0
572
#                 No error or warnign occurred.
573
#             -1
574
#                 Error: no installation detected.
575
#
576
function changeDefaultVersion {
577
  local versions=("${!1}")
578
  local linkdir="$2"
579

    
580
  # check whether an installation was detected
581
  if [ ${#versions[@]} -eq 0 ]; then
582
    printError "no installation detected\n"
583
    return -1
584
  else
585
    # print all available versions
586
    printInfo "choose the installation to switch to or type 'A' to abort:\n"
587
    for (( cnt=0; cnt<${#versions[@]}; ++cnt )); do
588
      printf "  %2u: %s\n" $(($cnt + 1)) ${versions[$cnt]}
589
    done
590

    
591
    # read user selection
592
    printLog "read user slection\n"
593
    local userinput=""
594
    while [[ ! "$userinput" =~ ^[0-9]+$ ]] || [ ! "$userinput" -gt 0 ] || [ ! "$userinput" -le ${#versions[@]} ] && [[ ! "$userinput" =~ ^[Aa]$ ]]; do
595
      read -p "your selection: " -e userinput
596
      printLog "user selection: $userinput\n"
597
      if [[ ! "$userinput" =~ ^[0-9]+$ ]] || [ ! "$userinput" -gt 0 ] || [ ! "$userinput" -le ${#versions[@]} ] && [[ ! "$userinput" =~ ^[Aa]$ ]]; then
598
        printWarning "Please enter an integer between 1 and ${#versions[@]} or 'A' to abort.\n"
599
      fi
600
    done
601

    
602
    if [[ "$userinput" =~ ^[Aa]$ ]]; then
603
      printWarning "aborted by user\n"
604
    else
605
      local idx=$((userinput - 1))
606
      # find and delete old links
607
      rm `find $linkdir -maxdepth 1 -type l | grep -Ev "*[0-9]\.[0-9]\.[0-9]"`
608
      # create new links
609
      local bindir=$(dirname ${versions[$idx]})
610
      ls $bindir | xargs -i ln -sf $bindir/{} $linkdir/{}
611
      printInfo "default version set to $(arm-none-eabi-gcc -dumpversion)\n"
612
    fi
613
  fi
614

    
615
  return 0
616
}
617

    
618
### main function of this script ###############################################
619
# The IDE setup lets the user select an IDE of choice.
620
# As of now, only QtCreator is supported.
621
#
622
# usage:      see function printHelp
623
# arguments:  see function printHelp
624
# return:     0
625
#                 No error or warning occurred.
626
#
627
function main {
628
  # print welcome/info text if not suppressed
629
  if [[ $@ != *"--noinfo"* ]]; then
630
    printWelcomeText
631
  else
632
    printf "######################################################################\n"
633
  fi
634
  printf "\n"
635

    
636
  # if --help or -h was specified, print the help text and exit
637
  if [[ $@ == *"--help"* || $@ == *"-h"* ]]; then
638
    printHelp
639
    printf "\n"
640
    quitScript
641
  fi
642

    
643
  # set log file if specified
644
  if [[ $@ == *"--log"* ]] || [[ $@ == *"--LOG"* ]]; then
645
    # get the parameter (file name)
646
    local cmdidx=1
647
    while [[ ! "${!cmdidx}" = "--log"* ]] && [[ ! "${!cmdidx}" = "--LOG"* ]]; do
648
      cmdidx=$[cmdidx + 1]
649
    done
650
    local cmd="${!cmdidx}"
651
    local logfile=""
652
    if [[ "$cmd" = "--log="* ]] || [[ "$cmd" = "--LOG="* ]]; then
653
      logfile=${cmd#*=}
654
    else
655
      local filenameidx=$((cmdidx + 1))
656
      logfile="${!filenameidx}"
657
    fi
658
    # optionally force silent appending
659
    if [[ "$cmd" = "--LOG"* ]]; then
660
      setLogFile --option=a --quiet "$logfile" LOG_FILE
661
    else
662
      setLogFile "$logfile" LOG_FILE
663
      printf "\n"
664
    fi
665
  fi
666
  # log script name
667
  printLog "this is $(realpath ${BASH_SOURCE[0]})\n"
668

    
669
  # detect installed versions and inform user
670
  local installedversions=()
671
  local currentversion=""
672
  detectInstalledVersions installedversions currentversion
673
  case "${#installedversions[@]}" in
674
    0)
675
      printInfo "no installation has been detected\n";;
676
    1)
677
      printInfo "1 installation has been detected:\n";;
678
    *)
679
      printInfo "${#installedversions[@]} installations have been detected:\n";;
680
  esac
681
  for (( idx=0; idx<${#installedversions[@]}; ++idx )); do
682
    if [ ${installedversions[$idx]} = "$currentversion" ]; then
683
      printInfo "  * ${installedversions[$idx]}\n"
684
    else
685
      printInfo "    ${installedversions[$idx]}\n"
686
    fi
687
  done
688
  printf "\n"
689

    
690
  # parse arguments
691
  local otherargs=()
692
  while [ $# -gt 0 ]; do
693
    if ( parseIsOption $1 ); then
694
      case "$1" in
695
        -h|--help) # already handled; ignore
696
          shift 1;;
697
        -i|--init)
698
          if [ -z "$currentversion" ]; then
699
            installNewVersion
700
          else
701
            installNewVersion --install=$(realpath $(dirname "$currentversion")/../../) --link=$(realpath $(dirname "$currentversion")/../../)
702
          fi
703
          printf "\n"; shift 1;;
704
        -c|--change)
705
          changeDefaultVersion installedversions[@] $(realpath $(dirname "$currentversion")/../../); printf "\n"; shift 1;;
706
        -q|--quit)
707
          quitScript; shift 1;;
708
        --log=*|--LOG=*) # already handled; ignore
709
          shift 1;;
710
        --log|--LOG) # already handled; ignore
711
          shift 2;;
712
        --noinfo) # already handled; ignore
713
          shift 1;;
714
        *)
715
          printError "invalid option: $1\n"; shift 1;;
716
      esac
717
    else
718
      otherargs+=("$1")
719
      shift 1
720
    fi
721
  done
722

    
723
  # interactive menu
724
  while ( true ); do
725
    # main menu info prompt and selection
726
    printInfo "GCC setup main menu\n"
727
    printf "Please select one of the following actions:\n"
728
    printf "  [I] - install another version\n"
729
    printf "  [C] - change default version\n"
730
    printf "  [Q] - quit this setup\n"
731
    local userinput=""
732
    readUserInput "IiCcQq" userinput
733
    printf "\n"
734

    
735
    # evaluate user selection
736
    case "$userinput" in
737
      I|i)
738
        if [ -z "$currentversion" ]; then
739
          installNewVersion
740
        else
741
          installNewVersion --install=$(realpath $(dirname "$currentversion")/../../) --link=$(realpath $(dirname "$currentversion")/../../)
742
        fi
743
        printf "\n";;
744
      C|c)
745
        changeDefaultVersion installedversions[@] $(realpath $(dirname "$currentversion")/../../); printf "\n";;
746
      Q|q)
747
        quitScript;;
748
      *) # sanity check (exit with error)
749
        printError "unexpected argument: $userinput\n";;
750
    esac
751
  done
752

    
753
  exit 0
754
}
755

    
756
################################################################################
757
# SCRIPT ENTRY POINT                                                           #
758
################################################################################
759

    
760
main "$@"