Statistics
| Branch: | Tag: | Revision:

amiro-os / tools / ide / QtCreator / QtCreatorSetup.sh @ f606e2bf

History | View | Annotate | Download (34.429 KB)

1
################################################################################
2
# AMiRo-OS is an operating system designed for the Autonomous Mini Robot       #
3
# (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:      checkCommands [<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 QtCreator 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] [--module=<module>] [-a|--all] [-c|--clean] [-w|--wipe] [-q|--quit] [--log=<file>]\n"
341
  printf "\n"
342
  printf "options:  -h, --help\n"
343
  printf "              Print this help text.\n"
344
  printf "          --module=<module>\n"
345
  printf "              Create project for a single module.\n"
346
  printf "          -a, --all\n"
347
  printf "              Create projects for all modules.\n"
348
  printf "          -c, --clean\n"
349
  printf "              Delete project files.\n"
350
  printf "          -w, --wipe\n"
351
  printf "              Delete project and .user files.\n"
352
  printf "          -q, --quit\n"
353
  printf "              Quit the script.\n"
354
  printf "          --log=<file>\n"
355
  printf "              Specify a log file.\n"
356
}
357

    
358
### read directory where to create/delete projects #############################
359
# Read the directory where to create/delete project files from user.
360
#
361
# usage:      getProjectDir <pathvar>
362
# arguments:  <pathvar>
363
#                 Variable to store the selected path to.
364
# return:     n/a
365
#
366
function getProjectDir {
367
  printLog "reading path for project files from user...\n"
368
  local amiroosdir=$(realpath $(dirname $(realpath ${BASH_SOURCE[0]}))/../../../)
369
  local input=""
370
  read -p "Path where to create/delete project files: " -i $amiroosdir -e input
371
  printLog "user selected path $(realpath $input)\n"
372
  eval $1="$(realpath $input)"
373
}
374

    
375
### retrieves the ARM-NONE-EABI-GCC include directory ##########################
376
# Retrieves the include directory of the currently set arm-none-eabi-gcc.
377
#
378
# usage:      retrieveGccIncludeDir <path>
379
# arguments:  <path>
380
#                 Variable to store the path to.
381
# return:    0
382
#                 No error or warning occurred.
383
#            -1
384
#                 Error: Command 'arm-none-eabi-gcc' not found.
385
#            -2
386
#                 Error: include directory could not be resolved
387
#
388
function retrieveGccIncludeDir {
389
  # retrieve binary path or link
390
  local binpath=$(which arm-none-eabi-gcc)
391
  local gccincpath=""
392
  if [ -z "$binpath" ]; then
393
    printError "command 'arm-none-eabi-gcc' not found\n"
394
    return -1
395
  else 
396

    
397
    # traverse any links
398
    while [ -L "$binpath" ]; do
399
      binpath=$(realpath $(dirname $binpath)/$(readlink $binpath))
400
    done
401
    printInfo "gcc-arm-none-eabi detected: $binpath\n"
402

    
403
    # return include path
404
    gccincpath=$(realpath $(dirname ${binpath})/../arm-none-eabi/include/)
405
    if [ ! -d "$gccincpath" ]; then
406
      printWarning "$gccincpath does not exist\n"
407
      return -2
408
    else
409
      eval $1="$gccincpath"
410
      return 0
411
    fi
412
  fi
413
}
414

    
415
### detect available modules ###################################################
416
# Detect all avalable modules supported by AMiRo-OS.
417
#
418
# usage:      detectModules <modulearray>
419
# arguments:  <modulearray>
420
#                 Array variable to store all detected modules to.
421
# return:     n/a
422
#
423
function detectModules {
424
  local modulesdir=$(realpath $(dirname $(realpath ${BASH_SOURCE[0]}))/../../../modules)
425
  local modules_detected=()
426

    
427
  # detect all available modules (via directories)
428
  for dir in $(ls -d ${modulesdir}/*/); do
429
    modules_detected[${#modules_detected[@]}]=$(basename $dir)
430
  done
431

    
432
  # set the output variable
433
  eval "$1=(${modules_detected[*]})"
434
}
435

    
436
### create project files for a single module ###################################
437
# Create project files for a single module.
438
#
439
# usage:      createModuleProject <modules> [-m|--module=<module>] [-p|--path=<path>] [--gcc=<path>] [-o|--out=<var>] [--gccout=<var>]
440
# arguments:  <modules>
441
#                 Array containing all modules available.
442
#             -m, --module <module>
443
#                 Name (folder name) of the module for which project files shall be generated.
444
#             -p, --path <path>
445
#                 Path where to create the project files.
446
#             --gcc=<path>
447
#                 Path to the GCC include directory.
448
#             -o, --out <var>
449
#                 Variable to store the path to.
450
#             --gccout=<var>
451
#                 Variable to store the path to the GCC include directory to.
452
#                 If this optional arguments is absent, ths function will ask for user input.
453
# return:     0
454
#                 No error or warning occurred.
455
#             1
456
#                 Aborted by user.
457
#             -1
458
#                 No modules available.
459
#             -2
460
#                 The specified <module> could not be found.
461
#             -3
462
#                 Parsing the project for the specified module failed.
463
#             -4
464
#                 Missing dependencies.
465
#
466
function createModuleProject {
467
  local userdir=$(pwd)
468
  local modulesdir=$(realpath $(dirname $(realpath ${BASH_SOURCE[0]}))/../../../modules)
469
  local modules=("${!1}")
470
  local module=""
471
  local moduleidx=""
472
  local projectdir=""
473
  local gccincludedir=""
474
  local outvar=""
475
  local gccoutvar=""
476

    
477
  # check dependencies
478
  checkCommands make
479
  if [ $? -ne 0 ]; then
480
    printError "Missing dependencies detected.\n"
481
    return -4
482
  fi
483

    
484
  # parse arguments
485
  local otherargs=()
486
  while [ $# -gt 0 ]; do
487
    if ( parseIsOption $1 ); then
488
      case "$1" in
489
        -m=*|--module=*)
490
          module="${1#*=}"; shift 1;;
491
        -m|--module)
492
          module="$2"; shift 2;;
493
        -p=*|--path=*)
494
          projectdir=$(realpath "${1#*=}"); shift 1;;
495
        -p|--path)
496
          projectdir=$(realpath "$2"); shift 2;;
497
        --gcc=*)
498
          gccincludedir=$(realpath "${1#*=}"); shift 1;;
499
        --gcc)
500
          gccincludedir=$(realpath "$2"); shift 2;;
501
        -o=*|--out=*)
502
          outvar=${1#*=}; shift 1;;
503
        -o|--out)
504
          outvar=$2; shift 2;;
505
        --gccout=*)
506
          gccoutvar=$(realpath "${1#*=}"); shift 1;;
507
        --gccout)
508
          gccoutvar=$(realpath "$2"); shift 2;;
509
        *)
510
          printError "invalid option: $1\n"; shift 1;;
511
      esac
512
    else
513
      otherargs+=("$1")
514
      shift 1
515
    fi
516
  done
517

    
518
  # sanity check for the modules variable
519
  if [ -z "${modules[*]}" ]; then
520
    printError "no modules available\n"
521
    return -1
522
  fi
523

    
524
  # select module
525
  if [ -z $module ]; then
526
    # list all available modules
527
    printInfo "choose a module or type 'A' to abort:\n"
528
    for (( idx=0; idx<${#modules[@]}; ++idx )); do
529
      printf "%4u: %s\n" $(($idx + 1)) "${modules[$idx]}"
530
    done
531
    # read user input
532
    printLog "read user selection\n"
533
    local userinput=""
534
    while [[ ! "$userinput" =~ ^[0-9]+$ ]] || [ ! "$userinput" -gt 0 ] || [ ! "$userinput" -le ${#modules[@]} ] && [[ ! "$userinput" =~ ^[Aa]$ ]]; do
535
      read -p "your selection: " -e userinput
536
      printLog "user selection: $userinput\n"
537
      if [[ ! "$userinput" =~ ^[0-9]+$ ]] || [ ! "$userinput" -gt 0 ] || [ ! "$userinput" -le ${#modules[@]} ] && [[ ! "$userinput" =~ ^[Aa]$ ]]; then
538
        printWarning "Please enter an integer between 1 and ${#modules[@]} or 'A' to abort.\n"
539
      fi
540
    done
541
    if [[ "$userinput" =~ ^[Aa]$ ]]; then
542
      printWarning "aborted by user\n"
543
      return 1
544
    fi
545
    # store selection
546
    moduleidx=$(($userinput - 1))
547
    module="${modules[$moduleidx]}"
548
    printf "\n"
549
  else
550
    # search all modules for the selected one
551
    for (( idx=0; idx<${#modules[@]}; ++idx )); do
552
      if [ "${modules[$idx]}" = "$module" ]; then
553
        moduleidx=$idx
554
        break
555
      fi
556
    done
557
    # error if the module could not be found
558
    if [ -z $moduleidx ]; then
559
      printError "module ($module) not available\n"
560
      return -2
561
    fi
562
  fi
563

    
564
  # read absolute project directory if required
565
  if [ -z "$projectdir" ]; then
566
    getProjectDir projectdir
567
    printf "\n"
568
  fi
569

    
570
  # check for existing project files
571
  local projectfiles="$(find ${projectdir} -maxdepth 1 -type f | grep -E "${module}\.(includes|files|config|creator)$")"
572
  IFS=$'\n'; projectfiles=($projectfiles); unset IFS
573
  if [ ! -z "${projectfiles[*]}" ]; then
574
    printWarning "The following files will be overwritten:\n"
575
    for pfile in ${projectfiles[@]}; do
576
      printWarning "\t$(basename $pfile)\n"
577
    done
578
    local userinput=""
579
    printInfo "Continue and overwrite? [y/n]\n"
580
    readUserInput "YyNn" userinput
581
    case "$userinput" in
582
      Y|y)
583
        ;;
584
      N|n)
585
        printWarning "Project generation for ${module} module aborted by user\n"
586
        return 1
587
        ;;
588
      *)
589
        printError "unexpected input: ${userinput}\n"; return -999;;
590
    esac
591
    printf "\n"
592
  fi
593

    
594
  # print message
595
  printInfo "generating QtCreator project files for the $module module...\n"
596

    
597
  # retrieve absolute GCC include path
598
  if [ -z "$gccincludedir" ]; then
599
    retrieveGccIncludeDir gccincludedir
600
  fi
601

    
602
  # change to project directory
603
  local amiroosrootdir=$(realpath $(dirname ${BASH_SOURCE[0]})/../../..)
604
  cd "$projectdir"
605

    
606
  # run make, but only run the GCC preprocessor and produce no binaries
607
  local sourcefiles=()
608
  local sourcefile=""
609
  local parse_state="WAIT_FOR_INCLUDE_OR_COMPILE"
610
  # capture all output from make and GCC and append the return value of make as last line
611
  printInfo "processing project (this may take a while)...\n"
612
  local rawout=$(make --directory ${amiroosrootdir}/modules/${module} --always-make USE_OPT="-v -E -H" USE_VERBOSE_COMPILE="no" OUTFILES="" 2>&1 && echo $?)
613
  # check whether the make call was successfull
614
  if [[ $(echo "${rawout}" | tail -n 1) != "0" ]]; then
615
    printError "executing 'make' in module directory failed\n"
616
    cd "$userdir"
617
    return -3
618
  else
619
    # cleanup
620
    make --directory ${amiroosrootdir}/modules/${module} clean &>/dev/null
621
  fi
622
  # extract file names from raw output
623
  IFS=$'\n'; rawout=($rawout); unset IFS
624
  for line in "${rawout[@]}"; do
625
    case $parse_state in
626
      WAIT_FOR_INCLUDE_OR_COMPILE)
627
        # lines stating included files look like:
628
        # ... <../relative/path/to/file>
629
        if [[ "$line" =~ ^\.+[[:blank:]].+\..+$ ]]; then
630
          sourcefile=${line##* }
631
          if [[ ! "$sourcefile" =~ ^/ ]]; then
632
            sourcefile=$(realpath ${amiroosrootdir}/modules/${module}/${sourcefile})
633
          fi
634
          sourcefiles[${#sourcefiles[@]}]="$sourcefile"
635
        # whenever the next source file is processed, a message appears like:
636
        # Compining <filnemame>
637
        elif [[ "$line" =~ ^Compiling[[:blank:]](.+\..+)$ ]]; then
638
          printf "."
639
          sourcefile=${BASH_REMATCH[1]}
640
          parse_state="WAIT_FOR_COMPILERCALL"
641
        fi;;
642
      WAIT_FOR_COMPILERCALL)
643
        # wait for the actual call of the compiler to retrieve the full path to the source file
644
        if [[ "$line" == *${sourcefile}* ]]; then
645
          line="${line%%${sourcefile}*}${sourcefile}"
646
          sourcefile=$(realpath ${amiroosrootdir}/modules/${module}/${line##* })
647
          sourcefiles[${#sourcefiles[@]}]="$sourcefile"
648
          parse_state="WAIT_FOR_INCLUDE_OR_COMPILE"
649
        fi;;
650
    esac
651
  done
652
  unset rawout
653
  printf "\n"
654
  # sort and remove duplicates
655
  IFS=$'\n'; sourcefiles=($(sort --unique <<< "${sourcefiles[*]}")); unset IFS
656

    
657
  # extract include paths
658
  local includes=()
659
  for source in ${sourcefiles[*]}; do
660
    includes[${#includes[@]}]="$(dirname ${source})"
661
  done
662
  # sort and remove duplicates
663
  IFS=$'\n'; includes=($(sort --unique <<< "${includes[*]}")); unset IFS
664

    
665
  # generate the .files file, containing all source files
666
  echo "" > ${projectdir}/${module}.includes
667
  for inc in ${includes[*]}; do
668
    echo "$inc" >> ${projectdir}/${module}.includes
669
  done
670
  # generate the .incldues file, containing all include paths
671
  echo "" > ${projectdir}/${module}.files
672
  for source in ${sourcefiles[*]}; do
673
    # skip GCC files
674
    if [[ ! "$source" =~ .*/gcc.* ]]; then
675
      echo "$source" >> ${projectdir}/${module}.files
676
    fi
677
  done
678
  # generate a default project configuration file if it doesn't exist yet
679
  if [ ! -f ${projectdir}/${module}.config ]; then
680
    echo "// Add predefined macros for your project here. For example:" > ${projectdir}/${module}.config
681
    echo "// #define YOUR_CONFIGURATION belongs here" >> ${projectdir}/${module}.config
682
  fi
683
  # generate a default .creator file if it doesn't exist yet
684
  if [ ! -f ${projectdir}/${module}.creator ]; then
685
    echo "[general]" > ${projectdir}/${module}.creator
686
  fi
687

    
688
  # go back to user directory
689
  cd $userdir
690

    
691
  # fill the output variables
692
  if [ ! -z "$outvar" ]; then
693
    eval $outvar="$projectdir"
694
  fi
695
  if [ ! -z "$gccoutvar" ]; then
696
    eval $gccoutvar="$gccincludedir"
697
  fi
698

    
699
  return 0
700
}
701

    
702
### create project files for all modules #######################################
703
# Create project files for all modules.
704
#
705
# usage:      createAllProjects <modules> [-p|--path=<path>] [--gcc=<path>] [-o|--out=<var>] [--gccout=<var>]
706
# arguments:  <modules>
707
#                 Array containing all modules available.
708
#             -p, --path <path>
709
#                 Path where to create the project files.
710
#             --gcc=<path>
711
#                 Path to the GCC include directory.
712
#             -o, --out <var>
713
#                 Variable to store the path to.
714
#             --gccout=<var>
715
#                 Variable to store the path to the GCC include directory to.
716
#                 If this optional arguments is absent, ths function will ask for user input.
717
# return:     0
718
#                 No error or warning occurred.
719
#             1
720
#                 Aborted by user.
721
#             -1
722
#                 No modules available.
723
#
724
function createAllProjects {
725
  local modules=("${!1}")
726
  local projectdir=""
727
  local gccincludedir=""
728
  local outvar=""
729
  local gccoutvar=""
730

    
731
  # parse arguments
732
  local otherargs=()
733
  while [ $# -gt 0 ]; do
734
    if ( parseIsOption $1 ); then
735
      case "$1" in
736
        -p=*|--path=*)
737
          projectdir=$(realpath "${1#*=}"); shift 1;;
738
        -p|--path)
739
          projectdir=$(realpath "$2"); shift 2;;
740
        --gcc=*)
741
          gccincludedir=$(realpath "${1#*=}"); shift 1;;
742
        --gcc)
743
          gccincludedir=$(realpath "$2"); shift 2;;
744
        -o=*|--out=*)
745
          outvar=${1#*=}; shift 1;;
746
        -o|--out)
747
          outvar=$2; shift 2;;
748
        --gccout=*)
749
          gccoutvar=$(realpath "${1#*=}"); shift 1;;
750
        --gccout)
751
          gccoutvar=$(realpath "$2"); shift 2;;
752
        *)
753
          printError "invalid option: $1\n"; shift 1;;
754
      esac
755
    else
756
      otherargs+=("$1")
757
      shift 1
758
    fi
759
  done
760

    
761
  # sanity check for the modules variable
762
  if [ -z "${modules[*]}" ]; then
763
    printError "no modules available\n"
764
    return -1
765
  fi
766

    
767
  # read absolute project directory if required
768
  if [ -z "$projectdir" ]; then
769
    getProjectDir projectdir
770
  fi
771

    
772
  # check for existing project files
773
  local projectfiles=()
774
  for module in ${modules[@]}; do
775
    local pfiles="$(find ${projectdir} -maxdepth 1 -type f | grep -E "${module}\.(includes|files|config|creator)$")"
776
    IFS=$'\n'; pfiles=($pfiles); unset IFS
777
    projectfiles=( ${projectfiles[*]} ${pfiles[*]} )
778
  done
779
  if [ ! -z "${projectfiles[*]}" ]; then
780
    printWarning "The following files will be removed:\n"
781
    for pfile in ${projectfiles[@]}; do
782
      printWarning "\t$(basename $pfile)\n"
783
    done
784
    local userinput=""
785
    printInfo "Continue and overwrite? [y/n]\n"
786
    readUserInput "YyNn" userinput
787
    case "${userinput}" in
788
      Y|y)
789
        for pfile in ${projectfiles[*]}; do
790
          rm "$pfile"
791
        done
792
        ;;
793
      N|n)
794
        printWarning "Project generation aborted by user\n"
795
        return 1
796
        ;;
797
      *)
798
        printError "unexpected input: ${userinput}\n"
799
        return 999
800
        ;;
801
    esac
802
  fi
803

    
804
  # print message
805
  printf "\n"
806
  printInfo "generating QtCreator project files for all modules...\n"
807

    
808
  # retrieve absolute GCC include path
809
  if [ -z "$gccincludedir" ]; then
810
    retrieveGccIncludeDir gccincludedir
811
  fi
812

    
813
  # iterate over all modules
814
  local retval=1
815
  for module in ${modules[@]}; do
816
    if [ $retval != 0 ]; then
817
      printf "\n"
818
    fi
819
    createModuleProject modules[@] --module="$module" --path="$projectdir" --gcc="$gccincludedir"
820
    retval=$?
821
  done
822

    
823
  return 0
824
}
825

    
826
### delete project files #######################################################
827
# Deletes all project files and optionally .user files, too.
828
#
829
# usage:      deleteProjects [-p|--path=<path>] [-m|--module=<module>] [-o|--out=<var>] [-w|-wipe]
830
# arguments:  -p, --path <path>
831
#                 Path where to delete the project files.
832
#             -m, --module <module>
833
#                 Module name for which the project files shall be deleted.
834
#             -o, --out <var>
835
#                 Variable to store the path to.
836
#             -w, --wipe
837
#                 Delete .user files as well.
838
# return:
839
#  -  0: no error
840
#
841
function deleteProjects {
842
  local modulename=""
843
  local projectdir=""
844
  local outvar=""
845
  local wipe=false
846
  local files=""
847

    
848
  # parse arguments
849
  local otherargs=()
850
  while [ $# -gt 0 ]; do
851
    if ( parseIsOption $1 ); then
852
      case "$1" in
853
        -p=*|--path=*)
854
          projectdir=$(realpath "${1#*=}"); shift 1;;
855
        -p|--path)
856
          projectdir=$(realpath "$2"); shift 2;;
857
        -m=*|--module=*)
858
          modulename="${1#*=}"; shift 1;;
859
        -m|--module)
860
          modulename="${2}"; shift 2;;
861
        -o=*|--out=*)
862
          outvar=${1#*=}; shift 1;;
863
        -o|--out)
864
          outvar=$2; shift 2;;
865
        -w|--wipe)
866
          wipe=true; shift 1;;
867
        *)
868
          printError "invalid option: $1\n"; shift 1;;
869
      esac
870
    else
871
      otherargs+=("$1")
872
      shift 1
873
    fi
874
  done
875

    
876
  # read absolute project directory if required
877
  if [ -z "$projectdir" ]; then
878
    getProjectDir projectdir
879
  fi
880

    
881
  # list all files to be deleted
882
  if [ -z "$modulename" ]; then
883
    if [ $wipe != true ]; then
884
      files=$(find "${projectdir}" -maxdepth 1 -type f | grep -E "^.+\.(includes|files|config|creator|cflags|cxxflags)$")
885
    else
886
      files=$(find "${projectdir}" -maxdepth 1 -type f | grep -E "^.+\.(includes|files|config|creator|cflags|cxxflags|creator(\.user(\..+)?)?)$")
887
    fi
888
  else
889
    if [ $wipe != true ]; then
890
      files=$(find "${projectdir}" -maxdepth 1 -type f | grep -E "^${modulename}\.(includes|files|config|creator|cflags|cxxflags)$")
891
    else
892
      files=$(find "${projectdir}" -maxdepth 1 -type f | grep -E "^${modulename}\.(includes|files|config|creator|cflags|cxxflags|creator(\.user(\..+)?)?)$")
893
    fi
894
  fi
895
  if [ ! -z "$files" ]; then
896
    printInfo "Deleting the following files:\n"
897
    while read line; do
898
      printInfo "\t$(basename ${line})\n"
899
      rm ${line} 2>&1 | tee -a $LOG_FILE
900
    done <<< "${files}"
901
  else
902
    printInfo "No project files found\n"
903
  fi
904

    
905
  # store the path to the output variable, if required
906
  if [ ! -z "$outvar" ]; then
907
    eval $outvar="$projectdir"
908
  fi
909

    
910
  return 0
911
}
912

    
913
### main function of this script ###############################################
914
# Creates, deletes and wipes QtCreator project files for the three AMiRo base modules.
915
#
916
# usage:      see function printHelp
917
# arguments:  see function printHelp
918
# return:     0
919
#                 No error or warning ocurred.
920
#
921
function main {
922
# print welcome/info text if not suppressed
923
  if [[ $@ != *"--noinfo"* ]]; then
924
    printWelcomeText
925
  else
926
    printf "######################################################################\n"
927
  fi
928
  printf "\n"
929

    
930
  # if --help or -h was specified, print the help text and exit
931
  if [[ $@ == *"--help"* || $@ == *"-h"* ]]; then
932
    printHelp
933
    printf "\n"
934
    quitScript
935
  fi
936

    
937
  # set log file if specified
938
  if [[ $@ == *"--log"* ]] || [[ $@ == *"--LOG"* ]]; then
939
    # get the parameter (file name)
940
    local cmdidx=1
941
    while [[ ! "${!cmdidx}" = "--log"* ]] && [[ ! "${!cmdidx}" = "--LOG"* ]]; do
942
      cmdidx=$[cmdidx + 1]
943
    done
944
    local cmd="${!cmdidx}"
945
    local logfile=""
946
    if [[ "$cmd" = "--log="* ]] || [[ "$cmd" = "--LOG="* ]]; then
947
      logfile=${cmd#*=}
948
    else
949
      local filenameidx=$((cmdidx + 1))
950
      logfile="${!filenameidx}"
951
    fi
952
    # optionally force silent appending
953
    if [[ "$cmd" = "--LOG"* ]]; then
954
      setLogFile --option=c --quiet "$logfile" LOG_FILE
955
    else
956
      setLogFile "$logfile" LOG_FILE
957
      printf "\n"
958
    fi
959
  fi
960
  # log script name
961
  printLog "this is $(realpath ${BASH_SOURCE[0]})\n"
962

    
963
  # detect available modules and inform user
964
  local modules=()
965
  detectModules modules
966
  case "${#modules[@]}" in
967
    0)
968
      printInfo "no module has been detected\n";;
969
    1)
970
      printInfo "1 module has been detected:\n";;
971
    *)
972
      printInfo "${#modules[@]} modules have been detected:\n"
973
  esac
974
  for (( idx=0; idx<${#modules[@]}; ++idx )); do
975
    printInfo "  - ${modules[$idx]}\n"
976
  done
977
  printf "\n"
978

    
979
  # parse arguments
980
  local otherargs=()
981
  while [ $# -gt 0 ]; do
982
    if ( parseIsOption $1 ); then
983
      case "$1" in
984
        -h|--help) # already handled; ignore
985
          shift 1;;
986
        -m=*|--module=*)
987
          createModuleProject modules[@] --module="${1#*=}"; printf "\n"; shift 1;;
988
        -m|--module)
989
          createModuleProject modules[@] --module="${2}"; printf "\n"; shift 2;;
990
        -a|--all)
991
          createAllProjects modules[@]; shift 1;;
992
        -c|--clean)
993
          deleteProjects; printf "\n"; shift 1;;
994
        -w|--wipe)
995
          deleteProjects --wipe; printf "\n"; shift 1;;
996
        -q|--quit)
997
          quitScript; shift 1;;
998
        --log=*|--LOG=*) # already handled; ignore
999
          shift 1;;
1000
        --log|--LOG) # already handled; ignore
1001
          shift 2;;
1002
        --noinfo) # already handled; ignore
1003
          shift 1;;
1004
        *)
1005
          printError "invalid option: $1\n"; shift 1;;
1006
      esac
1007
    else
1008
      otherargs+=("$1")
1009
      shift 1
1010
    fi
1011
  done
1012

    
1013
  # interactive menu
1014
  while ( true ); do
1015
    # main menu info prompt and selection
1016
    printInfo "QtCreator setup main menu\n"
1017
    printf "Please select one of the following actions:\n"
1018
    printf "  [M] - create a project for a single module\n"
1019
    printf "  [A] - create a project for all modules\n"
1020
    printf "  [C] - clean all project files\n"
1021
    printf "  [W] - wipe all project and .user files\n"
1022
    printf "  [Q] - quit this setup\n"
1023
    local userinput=""
1024
    readUserInput "MmAaCcWwQq" userinput
1025
    printf "\n"
1026

    
1027
    # evaluate user selection
1028
    case "$userinput" in
1029
      M|m)
1030
        createModuleProject modules[@]; printf "\n";;
1031
      A|a)
1032
        createAllProjects modules[@]; printf "\n";;
1033
      C|c)
1034
        deleteProjects; printf "\n";;
1035
      W|w)
1036
        deleteProjects --wipe; printf "\n";;
1037
      Q|q)
1038
        quitScript;;
1039
      *) # sanity check (exit with error)
1040
        printError "unexpected argument: $userinput\n";;
1041
    esac
1042
  done
1043

    
1044
  exit 0
1045
}
1046

    
1047
################################################################################
1048
# SCRIPT ENTRY POINT                                                           #
1049
################################################################################
1050

    
1051
main "$@"
1052