Snippets

Peter Scargill The Script

Created by Peter Scargill last modified
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
#!/bin/bash

## DON'T SELECT NPM UPDATE FOR NOW - NODE-RED WON'T START UP with NPM 5.0 and NODE 8.0
##
## This script was originally developed for the Raspberry Pi by Peter Scargill and Aidan Ruff.
## On non-Pi systems such as the FriendlyArm, don't expect GPIO ports to work out of the box.
## Also, for all systems, after you load this script and before running, you need to give
## it execute permissions and sure it is saved in Linux
## format (carriage returns only) - Notepad++ has this option under edit - eol conversion.
##
##
## IMPORTANT:-
## 1. Run ONLY as ROOT or PI users. If ROOT, PI user will be checked/created for you as the main
##    script must be run as pi.
##    User PI must be in the SUDO group. Other groups are added by the script.
## 2. When selection GPIO for non-Raspberry Pi devices note - specific support for ODROID C2 only
## 3. This script could take 3+ hours on a slow Pi Zero Wifi.... steer away from midnight to avoid any updates
##    such as dietpi upgrades etc.
## 4. For NEO (or similar) when asked by Armbian to make a new user - don't bother - script will do it.
## 5. For Node-Red on Pi Zero,  if serial port won't connect - look at serial port permissions in /dev/
## 6. Do not access this script as SUDO.
##
## For Log2RAM customising see this - https://github.com/azlux/log2ram
##
## See http://tech.scargill.net/orange-pi-pc-battle-of-the-pis/
##
## 08/09/2017 Added name change for Node-Red flows files - and tested Roseapple Pi with DietPi successfully
## 31/08/2017 Scrapped JED as MC is way better - added rpi-clone which works a treat with NANOPI
## 30/08/2017 Changed Webmin to NOT installed by default
## 24/08/2017 Tested Ubuntu on Odroid C2 and Roseapple Pi 
## 23/08/2017 Tested on the NanoPi K2 board running Ubuntu, installs perfectly (but note that
## FriendlyArm's WiringPi i2c is currently bust)
## 18/08/2017 Modified to handle latest Raspbian - Stretch - tested on RPI3
## 10/08/2017 Added "nrlog" utility for viewing and "tailing" - ie monitoring node-red logs in colour in
## a terminal
## 10/08/2017 Tested RPI3 - turns out the new GPIO nodes work perfectly on that - as does the mod use i2c
## from Node-Red - commenting out the RPI contrib GPIO as it nees ROOT permissions!!!!!
## see https://tech.scargill.net/the-real-raspberry-pi/
## 29/07/2017 Added rule to help node-red-contrib-opi-gpio utility with various boards using GPIO. See docs
## for that node - very promising - tried various nano boards with success
## 24/07/2017 Tested on the new NanoPi Neo Plus2 - worked a treat - I2c running - lovely
## 24/07/2017 Tested on a Raspberry Pi 2 using current Jessie
## 24/07/2017 Tested NanoPi Neo Air using Ubuntu Core Xenial 4.11.2
## 30/06/2017 added LOG FILE generation, same folder and name as script + datetime + .log - by MrShark
## 26/06/2017 added support for Debian 9 (Stretch), right now only tested in VM - by MrShark
## 26/06/2017 updated node 6.10.3 references to 6.11.0 references
## 26/04/2017 added option for Log2Ram
## 26/04/2017 Updated NodeJS as they took the previous version off the server!!!
## 29/03/2017 Tested on NanoPi Neo2 using Armbian nightly build of 27/03/2017 - added temperature and processor checks
## 25/03/2017 Tested on NanoPi M1+, host updating added and defaults on inputs added
## 18/03/2017 Tested on NanoPi M3
## 16/03/2017 Modifications to handle experimental Android Phone setup
## 10/03/2017 Modifications to detect and run with the Raspberry Pi Zero Lite (ARM6)
## 30/01/2017 Minor change to let the script work on Mint Linux on a laptop (Looks like Ubuntu)
## 14/01/2017 Updated webmin and habridge installations
## 04/01/2017 DietPi on Orange Pi Zero - installed perfectly - 1 hour. WIFI still iffy
## 04/07/2017 OrangePi Plus 2 - thanks to blog reader RoyG for that
## 26/12/2016 - complete re-hash for new menus

## Assuming access as pi user. Please note this script will NOT WORK AS ROOT - Must install as pi.

## 10/12/2016 Previous version tested on Pi3 with latest software Jessie
## 02/12/2016 Tested Roseapple Pi using Armbian - for Node-Red serial, had to
## enable permissions for the serial - everything worked first time
## 16/5/2016 Tested on NanoPi M1 - (got 3 UARTS out of the M1)
## 22/06/2016 added questions for non-Pi boards
## 22/06/2016 tested on NanoPi NEO using Armbian Jessie Server
## 28/12/2016 tested in DietPi and Xenial virtual machines
## http://www.armbian.com/donate/?f=Armbian_5.20_Nanopineo_Debian_jessie_3.4.112.7z
##
## NOTE:- removed node-red-contrib-admin from Node-red setup as you can now do installs in the palette manager within the editor
## Note also  - the PHONE setting is experimental assuming an Android phone, rooted and set up with "Linux Deploy"
## as per the relevant blog entry on tech.scargill.net
##
## Typically, sitting in your home directory (/home/pi) as user Pi you might want to use NANO to install this script
## and after giving the script execute permission (sudo chmod 0744 /home/pi/script.sh)
## you could run the file as ./script.sh
##
## Includes (if you tick them:
##    Mosquitto with web sockets (Port 9001)
##    SQLITE ( xxx.xxx.xxx.xxx/phpliteadmin),
##    Node-Red (xxx.xxx.xxx:1880)
##    Node-Red-Dashboard (xxx.xxx.xxx.xxx:1880/ui)
##    Webmin (xxx.xxx.xxx:10000)
##    Apache (xxx.xxx.xxx)
## as well as web page based items like mc and /phpsysinfo
##
## Note- on the Odroid C2 everything installed except webmin. After reboot this is what I did to get it running..
##    wget http://prdownloads.sourceforge.net/webadmin/webmin_1.850_all.deb
##    sudo dpkg --install webmin_1.850_all.deb
##    That complained about missing bits so I used...
##       sudo apt-get install -y perl libnet-ssleay-perl openssl libauthen-pam-perl
##       libpam-runtime libio-pty-perl apt-show-versions python
##    That seemed to fail and suggested I use...
##       sudo apt-get -y -f install
##    That installed the lot - working - something to do with it being 64 bits - but it works -
##    pi or root user and password and https://whatever:10000
##
## http://tech.scargill.net Thanks for contributions from Aidan Ruff and Antonio Fragola. Thank you.
##
## Node-Red security added as standard - using the ADMIN login. MQTT also has same ADMIN login.
##
## ROUTINES
## Here at the beginning, a load of useful routines - see further down

# Get time as a UNIX timestamp (seconds elapsed since Jan 1, 1970 0:00 UTC)
startTime="$(date +%s)"
columns=$(tput cols)
user_response=""

# High Intensity
IGreen='\e[0;92m'       # Green
IYellow='\e[0;93m'      # Yellow
IBlue='\e[0;94m'        # Blue
ICyan='\e[0;96m'        # Cyan
IWhite='\e[0;97m'       # White

# Bold High Intensity
BIRed='\e[1;91m'        # Red
BIGreen='\e[1;92m'      # Green
BIYellow='\e[1;93m'     # Yellow
BIPurple='\e[1;95m'     # Purple
BIMagenta='\e[1;95m'    # Purple
BICyan='\e[1;96m'       # Cyan
BIWhite='\e[1;97m'      # White

skip=0
other=0

clean_stdin()
{
    while read -r -t 0; do
        read -n 256 -r -s
    done
}

# Permanent loop until both passwords are the same..
function user_input {
    local VARIABLE_NAME=${1}
    local VARIABLE_NAME_1="A"
    local VARIABLE_NAME_2="B"
    while true; do
        printf "${BICyan}$2: ${BIWhite}";
        if [ "$3" = "hide" ] ; then
            stty -echo;
        fi
        read VARIABLE_NAME_1;
        stty echo;
        if [ "$3" = "hide" ] ; then
            printf "\n${BICyan}$2 (again) : ${BIWhite}";
            stty -echo;
            read VARIABLE_NAME_2;
            stty echo;
        else
            VARIABLE_NAME_2=$VARIABLE_NAME_1;
        fi
        if [ $VARIABLE_NAME_1 != $VARIABLE_NAME_2 ] ; then
            printf "\n${BIRed}Sorry, did not match!${BIWhite}\n";
        else
            break;
        fi
    done
    readonly ${VARIABLE_NAME}=$VARIABLE_NAME_1;
    if [ "$3" == "hide" ] ; then
        printf "\n";
    fi
}

stopit=0
other=0
yes=0
nohelp=0
hideother=0

timecount(){
    sec=30
    while [ $sec -ge 0 ]; do
        if [ $nohelp -eq 1 ]; then
            
            if [ $hideother -eq 1 ]; then
                printf "${BIPurple}Continue ${BIWhite}y${BIPurple}(es)/${BIWhite}n${BIPurple}(o)/${BIWhite}a${BIPurple}(ll)/${BIWhite}e${BIPurple}(nd)-  ${BIGreen}00:0$min:$sec${BIPurple} remaining\033[0K\r${BIWhite}"
            else
                printf "${BIPurple}Continue ${BIWhite}y${BIPurple}(es)/${BIWhite}o${BIPurple}(ther)/${BIWhite}e${BIPurple}(nd)-  ${BIGreen}00:0$min:$sec${BIPurple} remaining\033[0K\r${BIWhite}"
            fi
        else
            printf "${BIPurple}Continue ${BIWhite}y${BIPurple}(es)/${BIWhite}h${BIPurple}(elp)-  ${BIGreen}00:0$min:$sec${BIPurple} remaining\033[0K\r${BIWhite}"
        fi
        sec=$((sec-1))
        trap '' 2
        stty -echo
        read -t 1 -n 1 user_response
        stty echo
        trap - 2
        if [ -n  "$user_response" ]; then
            break
        fi
    done
}


task_start(){
    printf "\r\n"
    printf "${BIGreen}%*s\n" $columns | tr ' ' -
    printf "$1"
    clean_stdin
    skip=0
    printf "\n${BIGreen}%*s${BIWhite}\n" $columns | tr ' ' -
    elapsedTime="$(($(date +%s)-startTime))"
    printf "Elapsed: %02d hrs %02d mins %02d secs\n" "$((elapsedTime/3600%24))" "$((elapsedTime/60%60))" "$((elapsedTime%60))"
    clean_stdin
    if [ "$user_response" != "a" ]; then
        timecount
    fi
    echo -e "                                                                        \033[0K\r"
    if  [ "$user_response" = "e" ]; then
        printf "${BIWhite}"
        exit 1
    fi
    if  [ "$user_response" = "n" ]; then
        skip=1
    fi
    if  [ "$user_response" = "o" ]; then
        other=1
    fi
    if  [ "$user_response" = "h" ]; then
        stopit=1
    fi
    if  [ "$user_response" = "y" ]; then
        yes=1
    fi
    if [ -n  "$2" ]; then
        if [ $skip -eq 0 ]; then
            printf "${BIYellow}$2${BIWhite}\n"
        else
            printf "${BICyan}%*s${BIWhite}\n" $columns '[SKIPPED]'
        fi
    fi
}

task_end(){
    printf "${BICyan}%*s${BIWhite}\n" $columns '[OK]'
}


# credits to DietPi

CPU_TEMP_CURRENT='Unknown'
CPU_TEMP_PRINT='Unknown'
ACTIVECORES=$(grep -c processor /proc/cpuinfo)

#Array to store possible locations for temp read.
aFP_TEMPERATURE=(
    '/sys/class/thermal/thermal_zone0/temp'
    '/sys/devices/virtual/thermal/thermal_zone1/temp'
    '/sys/devices/platform/sunxi-i2c.0/i2c-0/0-0034/temp1_input'
    '/sys/class/hwmon/hwmon0/device/temp_label'
)

Obtain_Cpu_Temp(){
    for ((i=0; i<${#aFP_TEMPERATURE[@]}; i++))
    do
        if [ -f "${aFP_TEMPERATURE[$i]}" ]; then
            CPU_TEMP_CURRENT=$(cat "${aFP_TEMPERATURE[$i]}")
            # - Some devices (pine) provide 2 digit output, some provide a 5 digit ouput.
            #       So, If the value is over 1000, we can assume it needs converting to 1'c
            if (( $CPU_TEMP_CURRENT == 0 )); then
                continue
            fi
            if (( $CPU_TEMP_CURRENT >= 1000 )); then
                CPU_TEMP_CURRENT=$( echo -e "$CPU_TEMP_CURRENT" | awk '{print $1/1000}' | xargs printf "%0.0f" )
            fi
            if (( $CPU_TEMP_CURRENT >= 70 )); then
                CPU_TEMP_PRINT="\e[91mWarning: $CPU_TEMP_CURRENT'c\e[0m"
                elif (( $CPU_TEMP_CURRENT >= 60 )); then
                CPU_TEMP_PRINT="\e[38;5;202m$CPU_TEMP_CURRENT'c\e[0m"
                elif (( $CPU_TEMP_CURRENT >= 50 )); then
                CPU_TEMP_PRINT="\e[93m$CPU_TEMP_CURRENT'c\e[0m"
                elif (( $CPU_TEMP_CURRENT >= 40 )); then
                CPU_TEMP_PRINT="\e[92m$CPU_TEMP_CURRENT'c\e[0m"
                elif (( $CPU_TEMP_CURRENT >= 30 )); then
                CPU_TEMP_PRINT="\e[96m$CPU_TEMP_CURRENT'c\e[0m"
            else
                CPU_TEMP_PRINT="\e[96m$CPU_TEMP_CURRENT'c\e[0m"
            fi
            break
        fi
    done
}

LOGFILE=$HOME/$0-`date +%Y-%m-%d_%Hh%Mm`.log

printl() {
	printf $1
	echo -e $1 >> $LOGFILE
}

printstatus() {
    Obtain_Cpu_Temp
    h=$(($SECONDS/3600));
    m=$((($SECONDS/60)%60));
    s=$(($SECONDS%60));
    printf "\r\n${BIGreen}==\r\n== ${BIYellow}$1"
    printf "\r\n${BIGreen}== ${IBlue}Total: %02dh:%02dm:%02ds Cores: $ACTIVECORES Temperature: $CPU_TEMP_PRINT \r\n${BIGreen}==${IWhite}\r\n\r\n"  $h $m $s;
	echo -e "############################################################" >> $LOGFILE
	echo -e $1 >> $LOGFILE
}


############################################################################
##
## MAIN SECTION OF SCRIPT - action begins here
##
#############################################################################
##

printstatus "Welcome to THE SCRIPT!"

AQUIET="-qq"
NQUIET="-s"

# install sudo on devices without it
[ ! -x /usr/bin/sudo ] && apt-get $AQUIET -y update > /dev/null 2>&1 && apt-get $AQUIET -y install sudo 2>&1 | tee -a $LOGFILE

# Whiptail menu may already be installed by default, on the other hand maybe not.
sudo apt-get $AQUIET -y install whiptail ccze 2>&1 | tee -a $LOGFILE
# Another way - Xenial should come up in upper case in $DISTRO
. /etc/os-release
OPSYS=${ID^^}
echo -e OPSYS: $OPSYS >> $LOGFILE

printstatus "Grabbing some preliminaries..."

# test internet connection
sudo chmod u+s /bin/ping
if [[ "$(ping -c 1 23.1.68.60  | grep '100%' )" != "" ]]; then
    printl "${IRed}!!!! No internet connection available, aborting! ${IWhite}\r\n"
    exit 0
fi

# install lsb_release on devices without it
[ ! -x /usr/bin/lsb_release ] && apt-get $AQUIET -y update > /dev/null 2>&1 && apt-get $AQUIET -y install lsb-release 2>&1 | tee -a $LOGFILE
DISTRO=$(/usr/bin/lsb_release -rs)
CHECK64=$(uname -m)
echo -e DISTRO: $DISTRO >> $LOGFILE
echo -e CHECK64: $CHECK64 >> $LOGFILE

if [[ $OPSYS == *"UBUNTU"* ]]; then
    if [ $DISTRO != "16.04" ] ; then
        printl "${IRed}!!!! Wrong version of Ubuntu - not 16.04, aborting! ${IWhite}\r\n"
        exit 0
    fi
fi

# user pi existance/creation
echo -e USER: $USER >> $LOGFILE
if [[ $USER != "pi" ]]; then
    if [[ $USER == "root" ]]; then
        printf "\r\n${ICyan}Hello ROOT... ${IWhite}"
        getent passwd pi > /dev/null 2>&1
        if [ $? -eq 0 ]; then
            printf "${ICyan}user \"pi\" exists, please log-out as root and run script as pi.${IWhite}\r\n\r\n"
            usermod pi -g sudo
            echo "pi ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/pi
            chmod 0440 /etc/sudoers.d/pi
            chmod 4755 /usr/bin/sudo			
            cp $(readlink -f $0) /home/pi && chown pi.pi /home/pi/$0 && chmod 755 /home/pi/$0
            chown pi.pi $LOGFILE && chmod 644 $LOGFILE && cp $LOGFILE /home/pi
        else
            adduser --quiet --disabled-password --shell /bin/bash --home /home/pi --gecos "User" pi
            echo "pi:password" | chpasswd
            usermod pi -g sudo
            echo "pi ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/pi
            chmod 0440 /etc/sudoers.d/pi
            chmod 4755 /usr/bin/sudo
            printf "${ICyan}user PI created, password is \"password\". Please log-out as root and login as pi, and redo the procedure ${IWhite}\r\n\r\n"
            cp $(readlink -f $0) /home/pi && chown pi.pi /home/pi/$0 && chmod 755 /home/pi/$0
            chown pi.pi $LOGFILE && chmod 644 $LOGFILE && cp $LOGFILE /home/pi
        fi
        exit
    else
        printstatus "Leaving script as you are neither PI nor ROOT user."
        exit
    fi
else
	sudo touch /etc/AlreadyRun
fi

if [ ! -f /etc/AlreadyRun ]; then
	printstatus "Stopping IPV6 access"
	echo "net.ipv6.conf.all.disable_ipv6 = 1" | sudo tee -a /etc/sysctl.conf > /dev/null 2>&1
	echo "net.ipv6.conf.default.disable_ipv6 = 1" | sudo tee -a /etc/sysctl.conf > /dev/null 2>&1
	echo "net.ipv6.conf.lo.disable_ipv6 = 1" | sudo tee -a /etc/sysctl.conf > /dev/null 2>&1
	sudo sysctl -p

	printstatus "Allow remote root login and speed up SSH"
	sudo sed -i -e 's/PermitRootLogin no/PermitRootLogin yes/g' /etc/ssh/sshd_config
	sudo sed -i -e 's/PermitRootLogin without-password/PermitRootLogin yes/g' /etc/ssh/sshd_config
	sudo sed -i -e 's/PermitRootLogin prohibit-password/PermitRootLogin yes/g' /etc/ssh/sshd_config
	sudo sed -i -e 's/TCPKeepAlive yes/TCPKeepAlive no/g' /etc/ssh/sshd_config
	sudo sed -i '$ a UseDNS no' /etc/ssh/sshd_config
	sudo sed -i '$ a ClientAliveInterval 30' /etc/ssh/sshd_config
	sudo sed -i '$ a ClientAliveCountMax 100' /etc/ssh/sshd_config
	sudo /etc/init.d/ssh restart 2>&1 | tee -a $LOGFILE

	sudo update-alternatives --set newt-palette /etc/newt/palette.original 2>&1 | tee -a $LOGFILE

	# setup a progress bar
	echo "Dpkg::Progress-Fancy \"1\";" | sudo tee /etc/apt/apt.conf.d/99progressbar > /dev/null
	echo "APT::Color \"1\";" | sudo tee -a /etc/apt/apt.conf.d/99progressbar > /dev/null
	
	if [[ $OPSYS != *"RASPBIAN"* ]]; then
		printstatus "Adding user Pi permissions"
		for additionalgroup in cdrom games users i2c adm gpio input sudo netdev audio video dialout plugdev bluetooth ; do
			getent group ${additionalgroup} | grep -w -l pi || sudo adduser pi ${additionalgroup} 2>&1 | tee -a $LOGFILE
		done
	fi
    sudo apt-get install avahi-daemon avahi-utils -y 2>&1 | tee -a $LOGFILE
    sudo sed -i -e 's/use-ipv6=yes/use-ipv6=no/g' /etc/avahi/avahi-daemon.conf
else
        printstatus "Script is re-running, avoiding un-necessary repeats"
fi

if [[ $OPSYS == "LINUXMINT" ]]; then
    OPSYS="UBUNTU"
fi

if [[ $OPSYS != *"RASPBIAN"* ]] && [[ $OPSYS != *"DEBIAN"* ]] && [[ $OPSYS != *"UBUNTU"* ]] && [[ $OPSYS != *"DIETPI"* ]]; then
    printl "${BIRed}By the look of it, not one of the supported operating systems - aborting${BIWhite}\r\n"; exit
fi

username="user"
userpass="password123"

adminname="admin"
adminpass="password123"

newhostname=$(hostname)

SECONDS=0

if [[ $OPSYS == *"RASPBIAN"* ]];then
    MYMENU=$(whiptail --title "Main Raspberry Pi Selection" --checklist \
        "\nSelect items for your Pi as required then hit OK" 31 73 24 \
        "quiet" "Quiet(er) install - untick for lots of info " ON \
        "prereq" "Install general pre-requisites " ON \
        "phone" "Install on Android Smartphone - see blog" OFF \
        "mosquitto" "Install Mosquitto" ON \
        "apache" "Install Apache/PHP/SQLITE + PHPLITEADMIN " ON \
        "nodejs" "Install NodeJS" ON \
        "nodered" "Install Node-Red" ON \
        "webmin" "Install Webmin" OFF \
        "screen" "Install Screen" ON \
        "java" "Update Java" ON \
        "wiringpi" "Wiring Pi for the GPIO utility" OFF \
        "mpg123" "Install MPG123" ON \
        "modpass" "Mod USER and ADMIN passwords (password123)" ON \
        "phpsysinfo" "Install PHPSYSYINFO" ON \
        "addindex" "Add an index page and some CSS" ON \
        "passwords" "Update ROOT and PI user passwords" OFF \
        "installcu" "Install CU for serial VT100 Terminal" ON \
        "installmc" "Install MC+MCEDIT  file manager + editor " ON \
        "rpiclone" "Install RPI-Clone" ON \
        "habridge" "Install HA-bridge on port 82" OFF \
        "log2ram" "Install Log2RAM default 40Meg" OFF \
		"grafana" "Install Grafana and InfluxDB" OFF \
        "wolfram" "Remove Wolfram on a PI to save space" OFF \
        "office" "Remove LibreOffice on PI to save space" OFF 3>&1 1>&2 2>&3)
else
    MYMENU=$(whiptail --title "Main Non-Pi Selection" --checklist \
        "\nSelect items as required then hit OK" 32 74 25 \
        "quiet" "Quiet(er) install - untick for lots of info " ON \
        "prereq" "Install general pre-requisites" ON \
        "phone" "Install on Android Smartphone - see blog" OFF \
        "mosquitto" "Install Mosquitto" ON \
        "apache" "Install Apache/PHP/SQLITE + PHPLITEADMIN" ON \
        "nodejs" "Install NodeJS" ON \
        "nodered" "Install Node-Red" ON \
        "odroid" "Install ODROID C2-specific GPIO" OFF \
        "generich3" "Install GENERIC H3 GPIO (not Raspberry Pi) " OFF \
        "webmin" "Install Webmin" OFF \
        "screen" "Install Screen" ON \
        "java" "Update Java" ON \
        "modpass" "Mod USER and ADMIN passwords (password123)" ON \
        "mpg123" "Install MPG123" ON \
        "opimonitor" "Install OPI-Monitor - H3 ONLY" OFF \
        "phpsysinfo" "Install PHPSYSYINFO" ON \
        "addindex" "Add an index page and some CSS" ON \
        "passwords" "Update ROOT and PI user passwords" OFF \
        "installcu" "Install CU for serial VT100 Terminal" ON \
        "installmc" "Install MC+MCEDIT file manager + editor" ON \
        "rpiclone" "Install RPI-Clone" ON \
        "log2ram" "Install Log2RAM default 40Meg" OFF \
		"grafana" "Install Grafana and InfluxDB" OFF \
        "habridge" "Install HA-bridge on port 82" OFF 3>&1 1>&2 2>&3)
fi

if [[ $MYMENU != *"quiet"* ]]; then
    AQUIET=""
    NQUIET=""
fi

if [[ $MYMENU == "" ]]; then
    whiptail --title "Installation Aborted" --msgbox "Cancelled as requested." 8 78
    exit
fi

cd
newhostname=$(whiptail --inputbox "Enter new HOST name\nLeave the default value or select something new" 8 60 $newhostname 3>&1 1>&2 2>&3)

if [[ $MYMENU == *"modpass"* ]]; then
    
    username=$(whiptail --inputbox "Enter a USER name (example user)\nSpecifically for Node-Red Dashboard" 8 60 $username 3>&1 1>&2 2>&3)
    if [[ -z "${username// }" ]]; then
        printf "No user name given - aborting\r\n"; exit
    fi
    
    userpass=$(whiptail --passwordbox "Enter a user password" 8 60 3>&1 1>&2 2>&3)
    if [[ -z "${userpass// }" ]]; then
        printf "No user password given - aborting${BIWhite}\r\n"; exit
    fi
    
    userpass2=$(whiptail --passwordbox "Confirm user password" 8 60 3>&1 1>&2 2>&3)
    if  [ $userpass2 == "" ]; then
        printf "${BIRed}No password confirmation given - aborting${BIWhite}\r\n"; exit
    fi
    if  [ $userpass != $userpass2 ]
    then
        printf "${BIRed}Passwords don't match - aborting${BIWhite}\r\n"; exit
    fi
    
    adminname=$(whiptail --inputbox "Enter an ADMIN name (example admin)\nFor Node-Red and MQTT" 8 60 $adminname 3>&1 1>&2 2>&3)
    if [[ -z "${adminname// }" ]]; then
        printf "${BIRed}No admin name given - aborting${BIWhite}\r\n"
        exit
    fi
    
    adminpass=$(whiptail --passwordbox "Enter an admin password" 8 60 3>&1 1>&2 2>&3)
    if [[ -z "${adminpass// }" ]]; then
        printf "${BIRed}No user password given - aborting${BIWhite}\r\n"; exit
    fi
    
    adminpass2=$(whiptail --passwordbox "Confirm admin password" 8 60 3>&1 1>&2 2>&3)
    if  [ $adminpass2 == "" ]; then
        printf "${BIRed}No password confirmation given - aborting${BIWhite}\r\n"; exit
    fi
    if  [ $adminpass != $adminpass2 ]; then
        printf "${BIRed}Passwords don't match - aborting${BIWhite}\r\n"; exit
    fi
fi

if [[ $MYMENU == *"passwords"* ]]; then
    echo "Update your PI password"
    sudo passwd pi
    echo "Update your ROOT password"
    sudo passwd root
fi

if [[ $MYMENU == *"phone"* ]]; then
    echo "en_US.UTF-8 UTF-8" | sudo tee -a /etc/locale.gen > /dev/null
    # echo "service rsyslog stop" | sudo tee -a /etc/init.d/rc.local > /dev/null
    sudo update-rc.d rsyslog disable 2>&1 | tee -a $LOGFILE
    sudo locale-gen 2>&1 | tee -a $LOGFILE
    sudo sed -i -e 's#exit 0##g' /etc/rc.local
    echo "cd /home/pi/habridge" | sudo tee -a /etc/rc.local > /dev/null
    echo "[ -f /home/pi/habridge/habridge-log.txt ] && rm /home/pi/habridge/habridge-log.txt" | sudo tee -a /etc/rc.local > /dev/null
    echo "nohup /usr/bin/java -jar -Dserver.port=82 -Dconfig.file=/home/pi/habridge/data/habridge.config /home/pi/habridge/ha-bridge.jar > /home/pi/habridge/habridge-log.txt 2>&1 &" | sudo tee -a /etc/rc.local > /dev/null
    echo "chmod 777 /home/pi/habridge/habridge-log.txt" | sudo tee -a /etc/rc.local > /dev/null
    echo "exit 0" | sudo tee -a /etc/rc.local > /dev/null
fi

if [[ $MYMENU == *"wolfram"* ]]; then
    printstatus "Removing Wolfram"
    sudo apt-get $AQUIET -y purge wolfram-engine 2>&1 | tee -a $LOGFILE
fi

if [[ $MYMENU == *"office"* ]]; then
    printstatus "Removing LibreOffice"
    sudo apt-get $AQUIET -y remove --purge libreoffice* 2>&1 | tee -a $LOGFILE
fi

if [[ $MYMENU == *"prereq"* ]]; then
    printstatus "Installing pre-requisites (this could take some time)"
    sudo apt-get $AQUIET -y autoremove 2>&1 | tee -a $LOGFILE
    sudo apt-get $AQUIET  update 2>&1 | tee -a $LOGFILE
    sudo apt-get $AQUIET -y upgrade 2>&1 | tee -a $LOGFILE
    # fix for RPI treating PING as a root function - by Dave
    sudo setcap cap_net_raw=ep /bin/ping > /dev/null 2>&1
    sudo setcap cap_net_raw=ep /bin/ping6 > /dev/null 2>&1
    # Prerequisite suggested by Julian and adding in python-dev - and stuff I've added for SAMBA and telnet, and Common utilities

    sudo apt-get install $AQUIET -y apt-utils 2>&1 | tee -a $LOGFILE # a line on its own, as on some boards caused problems on next one...
sudo apt-get install $AQUIET -y bash-completion unzip build-essential git python-serial scons libboost-filesystem-dev libboost-program-options-dev libboost-system-dev libsqlite3-dev subversion libcurl4-openssl-dev libusb-dev python-dev cmake curl telnet usbutils gawk jq pv samba samba-common samba-common-bin winbind dosfstools parted gcc python-pip htop python-smbus i2c-tools 2>&1 | tee -a $LOGFILE
	sudo pip -q install psutil 2>&1 | tee -a $LOGFILE
	sudo -H pip -q install feedparser 2>&1 | tee -a $LOGFILE
    # This line to ensure name is resolved from hosts FIRST
    sudo sed -i '/\[global\]/a name resolve order = hosts wins bcast' /etc/samba/smb.conf
fi

if [[ $MYMENU == *"mosquitto"* ]]; then
    printstatus "Installing Mosquitto with Websockets"
    cd
    if [[ $OPSYS == *"UBUNTU"* ]]; then
        sudo apt-get $AQUIET -y install mosquitto mosquitto-clients 2>&1 | tee -a $LOGFILE
        [ $? -eq 0 ] && mosquitto=1 # mosquitto installed
    else
		if [[ $OPSYS == *"BIAN"* ]] && [[ $DISTRO == *"9."* ]]; then
			printl "${IRed}!!!! Installing stock Mosquitto from Debian 9! ${IWhite}\r\n"
		else
			wget http://repo.mosquitto.org/debian/mosquitto-repo.gpg.key -a $LOGFILE -O - | sudo apt-key add -
			echo "deb http://repo.mosquitto.org/debian jessie main" |sudo tee /etc/apt/sources.list.d/mosquitto-jessie.list
		fi
		sudo apt-get $AQUIET -y update && sudo apt-get $AQUIET -y install mosquitto mosquitto-clients 2>&1 | tee -a $LOGFILE
		[ $? -eq 0 ] && mosquitto=1 # mosquitto installed
    fi
    # add mosquitto mods+pass ONLY if it was installed...
    if [ $mosquitto -eq 1 ]; then
        sudo bash -c "echo -e \"listener 9001\nprotocol websockets\nlistener 1883\nallow_anonymous false\npassword_file /etc/mosquitto/passwords\" > /etc/mosquitto/conf.d/websockets.conf"
        sudo touch /etc/mosquitto/passwords
        sudo mosquitto_passwd  -b /etc/mosquitto/passwords $adminname $adminpass
        if [[ $OPSYS == *"RASPBIAN"* ]]; then
			echo -e "[Unit]\n\
Description=Mosquitto MQTT Broker daemon\n\
ConditionPathExists=/etc/mosquitto/mosquitto.conf\n\
After=network.target\n\
Requires=network.target\n\
\n\
[Service]\n\
Type=forking\n\
RemainAfterExit=no\n\
StartLimitInterval=0\n\
PIDFile=/var/run/mosquitto.pid\n\
ExecStart=/usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf -d\n\
ExecReload=/bin/kill -HUP $MAINPID\n\
Restart=on-failure\n\
RestartSec=2\n\
\n\
[Install]\n\
WantedBy=multi-user.target\n" | sudo tee /lib/systemd/system/mosquitto
			sudo systemctl  start mosquitto 2>&1 | tee -a $LOGFILE
			sudo systemctl enable mosquitto 2>&1 | tee -a $LOGFILE
		fi
	echo "alias mqttlog='tail -f /var/log/mosquitto/mosquitto.log | ccze -A'" | sudo tee -a /etc/bash.bashrc > /dev/null 2>&1
    else
        printl "${IRed}!!!! Mosquitto not installed! ${IWhite}\r\n"
    fi
fi

if [[ $MYMENU == *"wiringpi"* ]]; then
    printstatus "Installing WiringPi"
    cd
    git clone git://git.drogon.net/wiringPi 2>&1 | tee -a $LOGFILE
    # if git fails or folder does not exist, abort+report
    if [ $? -eq 0 ] && [ -d wiringPi ]; then
        cd ~/wiringPi
        ./build 2>&1 | tee -a $LOGFILE
    else
        printl "${IRed}!!!! Wiringpi not installed! ${IWhite}\r\n"
    fi 
fi

# Moved sqlite3 so that node-red sql node will install
# use back facing quotes in here - no idea why.
# Changed the order of installation of Apache etc to solve issues with ARMBIAN
#
if [[ $MYMENU == *"apache"* ]]; then
    printstatus "Installing Apache/PHP and Sqlite"
    cd
    sudo groupadd -f -g33 www-data
    
    if [[ $OPSYS != *"UBUNTU"* ]]; then
		if [[ $OPSYS == *"BIAN"* ]] && [[ $DISTRO == *"9."* ]]; then
			sudo apt-get $AQUIET -y install apache2 libapache2-mod-php7.0 sqlite3 php-sqlite3 php-xml php-mbstring 2>&1 | tee -a $LOGFILE
		else
			sudo apt-get $AQUIET -y install apache2 libapache2-mod-php5 sqlite3 php5-sqlite 2>&1 | tee -a $LOGFILE
		fi
        [ $? -eq 0 ] && apache=1 # apache installed
    else
        sudo apt-get $AQUIET -y install apache2 libapache2-mod-php7.0 sqlite3 php-sqlite3 php-xml php-mbstring 2>&1 | tee -a $LOGFILE
        [ $? -eq 0 ] && apache=1 # apache installed
    fi
    # if apache installed and /var/www/html exists, go on...
    if [ $apache -eq 1 ] && [ -d /var/www/html ]; then
        cd /var/www/html
        sudo mkdir phpliteadmin
        cd phpliteadmin
        sudo wget --no-check-certificate http://bitbucket.org/phpliteadmin/public/downloads/phpLiteAdmin_v1-9-7-1.zip -a $LOGFILE
        if [ $? -eq 0 ]; then
            sudo unzip phpLiteAdmin_v1-9-7-1.zip 2>&1 | tee -a $LOGFILE
            sudo mv phpliteadmin.php index.php
            sudo mv phpliteadmin.config.sample.php phpliteadmin.config.php
            sudo rm *.zip
            sudo mkdir themes
            cd themes
            sudo wget --no-check-certificate http://bitbucket.org/phpliteadmin/public/downloads/phpliteadmin_themes_2013-12-26.zip -a $LOGFILE
            sudo unzip phpliteadmin_themes_2013-12-26.zip 2>&1 | tee -a $LOGFILE
            sudo rm *.zip
            sudo sed -i -e 's#\$directory = \x27.\x27;#\$directory = \x27/home/pi/dbs/\x27;#g' /var/www/html/phpliteadmin/phpliteadmin.config.php
            sudo sed -i -e "s#\$password = \x27admin\x27;#\$password = \x27$adminpass\x27;#g" /var/www/html/phpliteadmin/phpliteadmin.config.php
            sudo sed -i -e "s#\$subdirectories = false;#\$subdirectories = true;#g" /var/www/html/phpliteadmin/phpliteadmin.config.php
            cd
        else
            printl "${IRed}!!!! PHPLITEADMIN not installed! ${IWhite}\r\n"
            cd ; rm -rf /var/www/html/phpliteadmin
        fi
        
        mkdir dbs
		sqlite3 /home/pi/dbs/iot.db << EOF
		CREATE TABLE IF NOT EXISTS \`pinDescription\` (
		 \`pinID\` INTEGER PRIMARY KEY NOT NULL,
		 \`pinNumber\` varchar(2) NOT NULL,
		 \`pinDescription\` varchar(255) NOT NULL
		);
		CREATE TABLE IF NOT EXISTS \`pinDirection\` (
		 \`pinID\` INTEGER PRIMARY KEY NOT NULL,
		 \`pinNumber\` varchar(2) NOT NULL,
		 \`pinDirection\` varchar(3) NOT NULL
		);
		CREATE TABLE IF NOT EXISTS \`pinStatus\` (
		 \`pinID\` INTEGER PRIMARY KEY NOT NULL,
		 \`pinNumber\` varchar(2)  NOT NULL,
		 \`pinStatus\` varchar(1) NOT NULL
		);
		CREATE TABLE IF NOT EXISTS \`users\` (
		 \`userID\` INTEGER PRIMARY KEY NOT NULL,
		 \`username\` varchar(28) NOT NULL,
		 \`password\` varchar(64) NOT NULL,
		 \`salt\` varchar(8) NOT NULL
		);
		CREATE TABLE IF NOT EXISTS \`device_list\` (
		 \`device_name\` varchar(80) NOT NULL DEFAULT '',
		 \`device_description\` varchar(80) DEFAULT NULL,
		 \`device_attribute\` varchar(80) DEFAULT NULL,
		 \`logins\` int(11) DEFAULT NULL,
		 \`creation_date\` datetime DEFAULT NULL,
		 \`last_update\` datetime DEFAULT NULL,
		 PRIMARY KEY (\`device_name\`)
		);

		CREATE TABLE IF NOT EXISTS \`readings\` (
		 \`recnum\` INTEGER PRIMARY KEY,
		 \`location\` varchar(20),
		 \`value\` int(11) NOT NULL,
		 \`logged\` timestamp not NULL DEFAULT CURRENT_TIMESTAMP ,
		 \`device_name\` varchar(40) not null,
		 \`topic\` varchar(40) not null
		);


		CREATE TABLE IF NOT EXISTS \`pins\` (
		 \`gpio0\` int(11) NOT NULL DEFAULT '0',
		 \`gpio1\` int(11) NOT NULL DEFAULT '0',
		 \`gpio2\` int(11) NOT NULL DEFAULT '0',
		 \`gpio3\` int(11) NOT NULL DEFAULT '0'
		);
		INSERT INTO PINS VALUES(0,0,0,0);
		CREATE TABLE IF NOT EXISTS \`temperature_record\` (
		 \`device_name\` varchar(64) NOT NULL,
		 \`rec_num\` INTEGER PRIMARY KEY,
		 \`temperature\` float NOT NULL,
		 \`date_time\` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
		);
		CREATE TABLE IF NOT EXISTS \`Device\` (
		 \`DeviceID\` INTEGER PRIMARY KEY,
		 \`DeviceName\` TEXT NOT NULL
		);
		CREATE TABLE IF NOT EXISTS \`DeviceData\` (
		 \`DataID\` INTEGER PRIMARY KEY,
		DeviceID INTEGER,
		 \`DataName\` TEXT, FOREIGN KEY(DeviceID ) REFERENCES Device(DeviceID)
		);
		CREATE TABLE IF NOT EXISTS \`Data\` (
		SequenceID INTEGER PRIMARY KEY,
		 \`DeviceID\` INTEGER NOT NULL,
		 \`DataID\` INTEGER NOT NULL,
		 \`DataValue\` NUMERIC NOT NULL,
		 \`epoch\` NUMERIC NOT NULL,
		 \`timestamp\` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP , FOREIGN KEY(DataID, DeviceID ) REFERENCES DeviceData(DAtaID, DeviceID )
		);
EOF
        
        cd
        chmod 777 /home/pi/dbs
        chmod 666 /home/pi/dbs/iot.db
        cd
    else
        printl "${IRed}!!!! Apache+PHP+SQLITE+PHPLITEADMIN NOT INSTALLED! ${IWhite}\r\n"
    fi
fi

if [[ $MYMENU == *"nodejs"* ]]; then
    printstatus "Installing NodeJS"
	LATESTNODE="v6.11.3"
    if [[ $(uname -m) == *"armv6"* ]]; then
        printstatus "Installing ARM6 version"
        wget --no-check-certificate https://nodejs.org/dist/$LATESTNODE/node-$LATESTNODE-linux-armv6l.tar.xz -a $LOGFILE
        [ $? -eq 0 ] && nodejs=1
        pv node-$LATESTNODE-linux-armv6l.tar.xz | tar -xJf -
        cd node-$LATESTNODE-linux-armv6l
        sudo cp -R * /usr/local/
        rm -f node-$LATESTNODE-linux-armv6l.tar.xz
    else
        if [[ $CHECK64 == *"aarch64"* ]]; then
            printstatus "Installing ARM64 version"
            wget --no-check-certificate https://nodejs.org/dist/$LATESTNODE/node-$LATESTNODE-linux-arm64.tar.xz -a $LOGFILE
            [ $? -eq 0 ] && nodejs=1
            pv node-$LATESTNODE-linux-arm64.tar.xz | tar -xJf -
            cd node-$LATESTNODE-linux-arm64
            sudo cp -R * /usr/local/
            rm -f node-$LATESTNODE-linux-arm64.tar.xz
        else
            curl -sL https://deb.nodesource.com/setup_6.x > nodesetup.sh
            sudo bash nodesetup.sh 2>&1 | tee -a $LOGFILE
            sudo apt-get $AQUIET -y install nodejs 2>&1 | tee -a $LOGFILE
            [ $? -eq 0 ] && nodejs=1
        fi
    fi
    if [ $nodejs -ne 1 ]; then
        printl "${IRed}!!!! NodeJS not installed! ${IWhite}\r\n"
    fi
fi

if [[ $MYMENU == *"nodered"* ]]; then
    #sudo npm cache clean
    printstatus "Installing Node-Red"
    # if nodejs does not exist, abort node-red install
    if [ -f /usr/bin/node ] || [ -f /usr/local/bin/node ]; then
        # prevent double additions to settings.js if it exists and is already modified
        if [ $(grep public ~/.node-red/settings.js 2> /dev/null | wc -l) -ne 1 ]; then
            sudo npm $NQUIET install -g --unsafe-perm node-red 2>&1 | tee -a $LOGFILE
            if [[ $MYMENU == *"phone"* ]]; then
                sudo wget -a $LOGFILE -O /etc/init.d/nodered https://gist.githubusercontent.com/bigmonkeyboy/9962293/raw/0fe19671b1aef8e56cbcb20f6677173f8495e539/nodered
                sudo chmod 755 /etc/init.d/nodered && sudo update-rc.d nodered defaults 2>&1 | tee -a $LOGFILE
            else
                echo | openssl s_client -showcerts -servername raw.githubusercontent.com -connect raw.githubusercontent.com:443 2>/dev/null | openssl x509 -inform pem -noout -text > /dev/null 2>&1
                [[ $? -ne 0 ]] && echo 151.101.128.133 raw.githubusercontent.com | sudo tee -a /etc/hosts
                sudo wget -a $LOGFILE --no-check-certificate https://raw.githubusercontent.com/node-red/raspbian-deb-package/master/resources/nodered.service -O /lib/systemd/system/nodered.service
                sudo wget -a $LOGFILE --no-check-certificate https://raw.githubusercontent.com/node-red/raspbian-deb-package/master/resources/node-red-start -O /usr/bin/node-red-start
                sudo wget -a $LOGFILE --no-check-certificate https://raw.githubusercontent.com/node-red/raspbian-deb-package/master/resources/node-red-stop -O /usr/bin/node-red-stop
                #sudo sed -i -e 's#=pi#=%USER#g' /lib/systemd/system/nodered.service
                sudo chmod +x /usr/bin/node-red-st*
                sudo systemctl daemon-reload 2>&1 | tee -a $LOGFILE
            fi
            
            cd
            mkdir .node-red
            cd .node-red
            printstatus "Installing Nodes (could take some time)"
            npm $NQUIET install moment node-red-contrib-config node-red-contrib-grove node-red-contrib-diode node-red-contrib-bigtimer \
			node-red-contrib-esplogin node-red-contrib-timeout node-red-node-openweathermap node-red-node-google node-red-node-sqlite \
			node-red-node-emoncms node-red-node-geofence node-red-contrib-ivona node-red-contrib-moment node-red-contrib-particle \
			node-red-contrib-web-worldmap node-red-contrib-sqldbs node-red-contrib-ramp-thermostat node-red-contrib-graphs i2c-bus \
			node-red-contrib-isonline node-red-node-ping node-red-node-random node-red-node-smooth node-red-contrib-npm node-red-node-arduino \
			node-red-contrib-file-function node-red-contrib-boolean-logic node-red-contrib-blynk-websockets node-red-contrib-chatbot \
			node-red-dashboard node-red-node-darksky node-red-node-serialport node-red-contrib-owntracks node-red-contrib-opi-gpio 2>&1 | tee -a $LOGFILE
            sudo npm $NQUIET install bcryptjs 2>&1 | tee -a $LOGFILE

			## this last bit of code is to ensure that node-red-contrib-opi-gpio can gain access to port bits!!
			getent group gpio || sudo groupadd gpio 2>&1 | tee -a $LOGFILE
			getent group gpio | grep -w -l pi || sudo adduser pi gpio 2>&1 | tee -a $LOGFILE
			[ ! -f /etc/udev/rules.d/99-com.rules ] && echo "KERNEL==\"gpio*\", RUN=\"/bin/sh -c 'chgrp -R gpio /sys/%p /sys/class/gpio && chmod -R g+w /sys/%p /sys/class/gpio'\"" | sudo tee -a /etc/udev/rules.d/99-com.rules > /dev/null
            
            if [[ $OPSYS == *"RASPBIAN"* ]]; then
                sudo sed -i -e 's#exit 0#chmod 777 /dev/ttyAMA0\nexit 0#g' /etc/rc.local
                sudo apt-get -y install python{,3}-rpi.gpio 2>&1 | tee -a $LOGFILE
                #npm $NQUIET install node-red-contrib-gpio 2>&1 | tee -a $LOGFILE
                #npm $NQUIET install raspi-io 2>&1 | tee -a $LOGFILE
            fi
            
            cd ~/.node-red/
            sudo service nodered start 2>&1 | tee -a $LOGFILE
			while [ ! -f settings.js ] ; do sudo sleep 1 ; done
			sudo service nodered stop  2>&1 | tee -a $LOGFILE
            echo " "
            bcryptadminpass=$(node -e "console.log(require('bcryptjs').hashSync(process.argv[1], 8));" $adminpass)
            bcryptuserpass=$(node -e "console.log(require('bcryptjs').hashSync(process.argv[1], 8));" $userpass)
            # echo Encrypted password: $bcryptpass
            cp settings.js settings.js.bak-pre-crypt
            
            datetimestamp=`date +%Y-%m-%d_%Hh%Mm`
            cd ~/.node-red
            # this will add the TOP piece of code for non-vol variables in settings.js
            gawk -i inplace -v INPLACE_SUFFIX=-$datetimestamp '!found && /module.exports/ { print " var mySettings;\n try {\n mySettings = require(\"/home/pi/.node-red/redvars.js\");\n } catch(err) {\n mySettings = {};\n }\n"; found=1 } 1' settings.js
            
            sudo sed -i -e 's#functionGlobalContext: {#\/\/ functionGlobalContext: {#g' settings.js
            sudo sed -i -e 's#\s\s\s\s\},#    \/\/ },#g' settings.js
            sudo sed -i -e 's#^\}#,#g' settings.js
            sudo echo " " > tmpfile
            sudo echo "    httpStatic: '/home/pi/.node-red/public'," >> tmpfile
            sudo echo "    functionGlobalContext: {" >> tmpfile
            sudo echo "        os:require('os')," >> tmpfile
            sudo echo "        moment:require('moment'), " >> tmpfile
            sudo echo "        fs:require('fs'), " >> tmpfile
            sudo echo "        i2c:require('i2c-bus'), " >> tmpfile
            sudo echo "        mySettings:mySettings " >> tmpfile
            sudo echo "    }," >> tmpfile
            sudo echo " " >> tmpfile
            sudo echo "    adminAuth: {" >> tmpfile
            sudo echo "        type: \"credentials\"," >> tmpfile
            sudo echo "        users: [{" >> tmpfile
            sudo echo "            username: \"$adminname\"," >> tmpfile
            sudo echo "            password: \"$bcryptadminpass\"," >> tmpfile
            sudo echo "            permissions: \"*\"" >> tmpfile
            sudo echo "        }]" >> tmpfile
            sudo echo "    }," >> tmpfile
            sudo echo " " >> tmpfile
            sudo echo "    httpNodeAuth: {user:\"$username\", pass:\"$bcryptuserpass\"}" >> tmpfile
            sudo echo "}" >> tmpfile
            sudo cat tmpfile >> settings.js
            sudo rm -f tmpfile
        else
            printl "${IRed}!!!! Settings.JS already present and modified, skipping! ${IWhite}\r\n"
        fi
        sed -i -e 's#\/\/\s*var fs = require("fs");#var fs = require("fs");\nvar i2c = require("i2c-bus");#' /home/pi/.node-red/settings.js
		## The next two lines are new (Sept 2017) and change the flows files to non-host-specific names - good for copying
		sed -i -e 's#\/\/flowFile#flowFile#' /home/pi/.node-red/settings.js
        sed -i -e 's#\/\/flowFilePretty#flowFilePretty#' /home/pi/.node-red/settings.js
        if [[ $MYMENU == *"phone"* ]]; then
            cd && sudo mv /etc/init.d/sendsigs .
        else
            sudo systemctl enable nodered.service 2>&1 | tee -a $LOGFILE
        fi
		## add a nice little command line utility (nrlog) for showing and tailing Node-Red scripts in colour
	    echo "alias nrlog='sudo journalctl -f -n 50 -u nodered -o cat | ccze -A'" | sudo tee -a /etc/bash.bashrc > /dev/null 2>&1
    else
        printl "${IRed}!!!! Node-Red not installed! ${IWhite}\r\n"
    fi
fi

if [[ $OPSYS != *"RASPBIAN"* ]]; then
    if [[ $MYMENU == *"odroid"* ]]; then
        printstatus "Installing Odroid GPIO"
        git clone https://github.com/hardkernel/wiringPi.git 2>&1 | tee -a $LOGFILE
        cd wiringPi
        ./build 2>&1 | tee -a $LOGFILE
        sudo chmod a+s /usr/local/bin/gpio
    fi
    if [[ $MYMENU == *"generich3"* ]]; then
        printstatus "Installing H3 GPIO"
        # Install NanoPi H3 based IO library
        git clone https://github.com/zhaolei/WiringOP.git -b h3 2>&1 | tee -a $LOGFILE
        cd WiringOP
        chmod +x ./build
        sudo ./build 2>&1 | tee -a $LOGFILE
        cd
    fi
fi

if [[ $MYMENU == *"webmin"* ]]; then
    printstatus "Installing Webmin at port 10000 (could take some time)"
    #cd
    #mkdir webmin
    #cd webmin
    #wget --no-check-certificate http://prdownloads.sourceforge.net/webadmin/webmin-1.831.tar.gz
    #sudo gunzip -q webmin-1.831.tar.gz
    #tar -xf webmin-1.831.tar
    #sudo rm *.tar
    #cd webmin-1.831
    #sudo ./setup.sh /usr/local/Webmin
    wget -a $LOGFILE http://www.webmin.com/jcameron-key.asc -O - | sudo apt-key add -
    echo "deb http://download.webmin.com/download/repository sarge contrib" | sudo tee /etc/apt/sources.list.d/webmin.list > /dev/null
    sudo apt-get $AQUIET -y update 2>&1 | tee -a $LOGFILE
    sudo apt-get $AQUIET -y install webmin 2>&1 | tee -a $LOGFILE
    # http vs https: if you want unsecure http access on port 10000 instead of https, uncomment next line
    sudo sed -i -e 's#ssl=1#ssl=0#g' /etc/webmin/miniserv.conf
fi

if [[ $MYMENU == *"mpg123"* ]]; then
    printstatus "Installing MPG123"
    sudo apt-get $AQUIET -y install mpg123 2>&1 | tee -a $LOGFILE
fi

#
# This works a treat on the NanoPi NEO using H3 and Armbian - should not do any harm on other systems as it's not installed!
#
if [[ $MYMENU == *"opimonitor"* ]]; then
    printstatus "Installing Armbian Monitor"
    sudo armbianmonitor -r 2>&1 | tee -a $LOGFILE
fi

if [[ $MYMENU == *"screen"* ]]; then
    printstatus "Installing Screen"
    sudo apt-get -y $AQUIET install screen 2>&1 | tee -a $LOGFILE
fi

if [[ $MYMENU == *"habridge"* ]]; then
    printstatus "Installing HA-Bridge on port 82"
    #sudo sed -i -e 's#80#81#g' /etc/apache2/ports.conf
    #sudo sed -i -e 's#80#81#g' /etc/apache2/sites-enabled/000-default.conf
    #sudo service apache2 restart
    ## now to install HA-Bridge on port 82 and get it running from power up.
    cd ~
    mkdir habridge
    cd habridge
    #wget https://github.com/bwssytems/ha-bridge/releases/download/v3.5.1/ha-bridge-3.5.1.jar -O ~/habridge/ha-bridge.jar
    curl -s https://api.github.com/repos/bwssytems/ha-bridge/releases/latest | jq --raw-output '.assets[0] | .browser_download_url' | wget -a $LOGFILE -i - -O ~/habridge/ha-bridge.jar
    echo -e "[Unit]\n\
Description=HA Bridge\n\
Wants=network.target\n\
After=network.target\n\
\n\
[Service]\n\
Type=simple\n\
ExecStart=/usr/bin/java -jar -Dserver.port=82 -Dconfig.file=/home/pi/habridge/data/habridge.config /home/pi/habridge/ha-bridge.jar\n\
\n\
[Install]\n\
    WantedBy=multi-user.target\n" | sudo tee /lib/systemd/system/habridge.service
    sudo systemctl  start habridge.service 2>&1 | tee -a $LOGFILE
    sudo systemctl enable habridge.service 2>&1 | tee -a $LOGFILE
fi

if [[ $MYMENU == *"java"* ]]; then
    printstatus "Installing/Updating Java"
	if [[ $OPSYS == *"BIAN"* ]] && [[ $DISTRO == *"9."* ]]; then
		sudo apt-get $AQUIET -y install software-properties-common dirmngr 2>&1 | tee -a $LOGFILE
		sudo add-apt-repository "deb http://ppa.launchpad.net/webupd8team/java/ubuntu yakkety main" 2>&1 | tee -a $LOGFILE
		sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys C2518248EEA14886 2>&1 | tee -a $LOGFILE
	else
		echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu xenial main" | sudo tee /etc/apt/sources.list.d/webupd8team-java.list
		echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu xenial main" | sudo tee -a /etc/apt/sources.list.d/webupd8team-java.list
		sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886 2>&1 | tee -a $LOGFILE
    fi
	sudo apt-get $AQUIET update 2>&1 | tee -a $LOGFILE
    echo debconf shared/accepted-oracle-license-v1-1 select true | sudo debconf-set-selections
    echo debconf shared/accepted-oracle-license-v1-1 seen true | sudo debconf-set-selections
    sudo apt-get $AQUIET -y install oracle-java8-installer 2>&1 | tee -a $LOGFILE
fi

if [[ $MYMENU == *"phpsysinfo"* ]]; then
    printstatus "Installing PHPSysInfo"
    #	sudo apt-get $AQUIET -y install phpsysinfo
    #	sudo ln -s /usr/share/phpsysinfo /var/www/html
    if [ -d /var/www/html ]; then
		cd /var/www/html
		sudo git clone https://github.com/phpsysinfo/phpsysinfo.git 2>&1 | tee -a $LOGFILE
		sudo cp /var/www/html/phpsysinfo/phpsysinfo.ini.new /var/www/html/phpsysinfo/phpsysinfo.ini
    else
        printl "${IRed}!!!! Apache+PHP not installed! ${IWhite}\r\n"
    fi
fi

# you may want to use these on a Pi or elsewhere to force either a graphical or command line environment
#sudo systemctl set-default multi-user.target
#sudo systemctl set-default graphical.target

if [[ $MYMENU == *"upgradenpm"* ]]; then
    printstatus "Upgrading NPM to the latest version"
    sudo npm $NQUIET install npm@latest -g 2>&1 | tee -a $LOGFILE
fi

# Add CU to enable serial VT100 mode for terminals
if [[ $MYMENU == *"installcu"* ]]; then
    printstatus "Installing CU"
    sudo apt-get $AQUIET -y install cu 2>&1 | tee -a $LOGFILE
fi

if [[ $MYMENU == *"installmc"* ]]; then
    printstatus "Installing MC File manager and editor"
    sudo apt-get -y $AQUIET install mc 2>&1 | tee -a $LOGFILE
fi

if [[ $MYMENU == *"rpiclone"* ]]; then
    printstatus "Installing RPI-Clone"
	cd
	sudo git clone https://github.com/billw2/rpi-clone.git
	cd rpi-clone
	sudo cp rpi-clone /usr/local/sbin
	cd
	sudo rm -r rpi-clone
fi

if [[ $MYMENU == *"log2ram"* ]]; then
    printstatus "Installing Log2Ram"
    cd
	git clone https://github.com/azlux/log2ram.git 2>&1 | tee -a $LOGFILE
    cd log2ram
    chmod +x install.sh
    sudo ./install.sh 2>&1 | tee -a $LOGFILE
	cd
fi

# Drop in an index file and css for a menu page
if [[ $MYMENU == *"addindex"* ]]; then
    printstatus "Adding index page and CSS"
    if [ -d /var/www/html ]; then
 		sudo wget -a $LOGFILE $AQUIET http://www.scargill.net/iot/index.html -O /var/www/html/index.html
		sudo wget -a $LOGFILE $AQUIET http://www.scargill.net/iot/reset.css -O /var/www/html/reset.css
    else
        printl "${IRed}!!!! Apache+PHP not installed! ${IWhite}\r\n"
    fi
fi

if [[ $MYMENU == *"grafana"* ]]; then
	printstatus "Installing Grafana and Influxdb"
	cd
	sudo apt-get $AQUIET -y update 2>&1 | tee -a $LOGFILE
	sudo apt-get $AQUIET install -y apt-transport-https curl 2>&1 | tee -a $LOGFILE
	curl -sL https://repos.influxdata.com/influxdb.key | sudo apt-key add -
	test $VERSION_ID = "8" && echo "deb https://repos.influxdata.com/debian jessie stable" | sudo tee /etc/apt/sources.list.d/influxdb.list
	test $VERSION_ID = "9" && echo "deb https://repos.influxdata.com/debian jessie stable" | sudo tee /etc/apt/sources.list.d/influxdb.list
	test $VERSION_ID = "16.04" && echo "deb https://repos.influxdata.com/ubuntu xenial stable" | sudo tee /etc/apt/sources.list.d/influxdb.list
	curl https://bintray.com/user/downloadSubjectPublicKey?username=bintray | sudo apt-key add -
	[[ $OPSYS == *"BIAN"* ]] && [[ $(uname -m) == *"armv6"* ]] && echo "deb https://dl.bintray.com/fg2it/deb-rpi-1b jessie main" | sudo tee -a /etc/apt/sources.list.d/grafana.list
	[[ $OPSYS == *"BIAN"* ]] && [[ $(uname -m) == *"armv7l"* ]] && echo "deb https://dl.bintray.com/fg2it/deb jessie main" | sudo tee -a /etc/apt/sources.list.d/grafana.list
	[[ $OPSYS == *"UBUNTU"* ]] && [[ $(uname -m) == *"aarch64"* ]] && sudo dpkg --add-architecture armhf && echo "deb [arch=armhf] https://dl.bintray.com/fg2it/deb jessie main" | sudo tee -a /etc/apt/sources.list.d/grafana.list
	[[ $OPSYS == *"UBUNTU"* ]] && [[ $(uname -m) != *"aarch64"* ]] && echo "deb https://dl.bintray.com/fg2it/deb jessie main" | sudo tee -a /etc/apt/sources.list.d/grafana.list
	sudo apt-get $AQUIET -y remove --purge grafana grafana-data 2>&1 | tee -a $LOGFILE
	sudo rm -rf /var/log/grafana /etc/grafana
	sudo apt-get $AQUIET -y autoremove 2>&1 | tee -a $LOGFILE
	sudo apt-get $AQUIET -y update 2>&1 | tee -a $LOGFILE
	if [[ $(uname -m) == *"aarch64"* ]]; then
		sudo apt-get install $AQUIET -y influxdb grafana:armhf 2>&1 | tee -a $LOGFILE
	else
		sudo apt-get install $AQUIET -y influxdb grafana 2>&1 | tee -a $LOGFILE
	fi
	[ $? -eq 0 ] && grafana=1 # grafana installed
	if [ $grafana -eq 1 ]; then
		#sudo sed -i -e 's/.*auth-enabled = false/  auth-enabled = true/g' /etc/influxdb/influxdb.conf
		sudo systemctl daemon-reload 2>&1 | tee -a $LOGFILE
		sudo systemctl enable influxdb 2>&1 | tee -a $LOGFILE
		sudo systemctl start influxdb 2>&1 | tee -a $LOGFILE
		sudo systemctl enable grafana-server 2>&1 | tee -a $LOGFILE
		sudo systemctl start grafana-server 2>&1 | tee -a $LOGFILE
		sudo wget https://dl.influxdata.com/chronograf/nightlies/chronograf_nightly_armhf.deb
		sudo dpkg -i chronograf_nightly_armhf.deb 2>&1 | tee -a $LOGFILE
		sudo systemctl enable chronograf 2>&1 | tee -a $LOGFILE
		sudo systemctl start chronograf 2>&1 | tee -a $LOGFILE
    else
        printl "${IRed}!!!! GRAFANA AND INFLUXDB NOT INSTALLED! ${IWhite}\r\n"
    fi
fi


sudo rm -rf /var/cache/apt/archives/apt-fast
sudo apt-get $AQUIET -y clean 2>&1 | tee -a $LOGFILE

myip=$(hostname -I)
thehostname=$(hostname)
echo $newhostname | sudo tee /etc/hostname > /dev/null 2>&1
sudo sed -i '/^127.0.1.1/ d' /etc/hosts > /dev/null 2>&1
echo 127.0.1.1 $newhostname | sudo tee -a /etc/hosts > /dev/null 2>&1
sudo /etc/init.d/hostname.sh > /dev/null 2>&1

printstatus "All done."
printf "${BIGreen}== ${BIYELLOW}When complete, remove the script from the /home/pi directory.\r\n"
printf "${BIGreen}==\r\n"
printf "${BIGreen}== ${BIPurple}Current IP: %s${BIWhite}\r\n" "$myip"
printf "${BIGreen}== ${BIPurple}Existing Hostname: %s  New Hostname: %s${BIWhite}\r\n\r\n" "$thehostname" "$newhostname"
echo -e Current IP: $myip  Hostname: $thehostname >> $LOGFILE
echo -e Hostname: $newhostname >> $LOGFILE
echo -e NPM: $(npm -v) >> $LOGFILE
echo -e PHP: $(php -v) >> $LOGFILE
echo -e NODE: $(node -v) >> $LOGFILE
echo -e MQTT: $(/usr/sbin/mosquitto --help | grep version) >> $LOGFILE
sudo grep -h ^deb /etc/apt/sources.list /etc/apt/sources.list.d/* 2>&1 >> $LOGFILE
printstatus  "ALL DONE - PLEASE REBOOT NOW THEN TEST"

Comments (0)