aboutsummaryrefslogtreecommitdiffstats
path: root/GNS3/gns3-install-on-local-server.sh
blob: fd8b1b5f330442a4070c32144849f1bad544466a (plain)
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
#!/bin/bash
########################################################################################################################
# gns3-install-on-local-server.sh
########################################################################################################################
#
# All rights reserved Ⓒ 2017-2023 sdxlive.com
#
# Written by Jean-Christophe Manciot <jcmanciot@sdxlive.com>
#
# Licensed under a GPLv3 License.
# You may not use this file except in compliance with the License. You may obtain a copy of the License at
#
#    https://www.gnu.org/licenses/gpl-3.0.md
#
# The licensor cannot revoke these freedoms as long as you follow the license terms.
#
# Attribution — You must give appropriate credit, provide a link to the license, and indicate if changes were made. 
# You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.
#
########################################################################################################################

########################################################################################################################
#
# Installing GNS3 as a Service on a recent remote Debian/Ubuntu bare-metal/VM server inside an OpenVPN tunnel.
# The server must be located on a local LAN/WLAN downstream from the Internet router(s).
# This sets up all the required packages.
# An OpenVPN management interface has also been setup to enable management commands with 'telnet 127.0.0.1 1195' on the 
# server.
# The security of the whole process has been enforced and hardened.
#
########################################################################################################################
#
# Requirements:
# ------------
#
# - We assume that this script is run as **root**.
#
########################################################################################################################
#
# Parameters:
# ----------
#
# The follwoing parameters are all optional, except --username:
# --apt-sources-url=<URL>:                      URL of latest stable Debian/Ubuntu APT sources
#                                               By default, it is http://deb.debian.org/debian or http://archive.ubuntu.com/ubuntu
# --gns3-port=<port_number>                     Port number which GNS3 server listens to
#                                               By default, it is 3080
# --openvpn-tunnel-ip-address=<ip_address>      OpenVPN tunnel IPv4 address on which GNS3 server listens
#                                               By default, it is 172.31.255.1
# --repository=<gns3|jc-manciot>:               Choose a repository between:
#                                                       + gns3: official GNS3 repository
#                                                       + jc-manciot: latest deb packages including GNS3 on the latest stable 
#                                                         Debian/Ubuntu release for x86_64 architectures
#                                               By default, it is jc-manciot.
# --username=<username>:                        on the server
# --without-new-apt-sources:                    Don't install new /etc/apt/sources.list
#                                               By default, on Debian, the follwoing are installed in /etc/apt/sources.list:
#                                                       + deb http://deb.debian.org/debian/debian testing main contrib non-free
#                                                       + deb deb http://security.debian.org/ testing/updates main contrib non-free
#                                               By default, on Ubuntu, the follwoing are installed /etc/apt/sources.list:
#                                                       + deb http://archive.ubuntu.com/ubuntu <os_code_name> main restricted multiverse universe
#                                                       + deb http://archive.ubuntu.com/ubuntu <os_code_name>-updates main restricted multiverse universe
#                                                       + deb http://archive.ubuntu.com/ubuntu <os_code_name>-security main restricted multiverse universe
# --without-openvpn:                            Don't install Open VPN: the communications with GNS3 server won't be encrypted
#                                               By default, an Open VPN is installed & configured.
# --without-openvpn-purge:                      Don't purge OpenVPN prior to its reinstallation if it is set to be used
#                                               By default, openVPN is purged before its installation.
# --without-ufw-gns3-port:                      Don't open GNS3 port on UFW firewall.
#                                               By default, UFW is used and GNS3 port is allowed for all sources within or outside  
#                                               OpenVPN tunnel depending on the configuration.
#                                               3080 port and tcp/5000:10000 console ports must be allowed manually somehow on UFW for GNS3 server
#                                               to be able to connect to its client(s).
# --without-ufw-openvpn-port:                   Don't open openvpn port on UFW firewall.
#                                               By default, UFW is used and openVPN port is allowed for all sources.
#                                               udp/1194 port must be allowed manually somehow on UFW for the OpenVPN tunnel to work.
# --without-ufw-ssh-port:                       Don't open ssh port on UFW firewall.
#                                               By default, UFW is used and ssh port is allowed for all sources.
#                                               tcp/22 port must be allowed manually somehow on UFW beforehand to be able to:
#                                                       + keep the current SSH session alive
#                                                       + retrieve the OpenVPN bundle.
# --without-unstable-repository:                Use only JC Manciot's DR/PPA stable repository
#                                               By default, stable & unstable JC Manciot's DR/PPA are used
# --help
#
#######################################################################################################################
#
# Usage:
# -----
#
# ssh root@<remote_server_ip_address>
#
# Inside the server terminal:
# --------------------------
# sudo -i
# curl https://git.sdxlive.com/DR/plain/GNS3/gns3-install-on-local-server.sh > gns3-install-on-local-server.sh
# curl https://git.sdxlive.com/DR/plain/Security/openvpn-gen.sh > openvpn-gen.sh
# chmod +x gns3-install-on-remote-server.sh openvpn-gen.sh
# chmod +x gns3-install-on-local-server.sh
# ./gns3-install-on-local-server.sh --username=<username> --without-ufw-gns3-port
# reboot
# 
# ssh root@<remote_server_ip_address>
#
# Then follow the instructions on the screen once the server has restarted
#
########################################################################################################################
# set -x
# Allowing extended pattern matching
shopt -s extglob

function help 
{
        printf "%s\n" "______________________________________________________________________________________________________________" >&2
        printf "%s\n" "Installing GNS3-as-a-Service on a recent remote Debian/Ubuntu bare-metal/VM server located on a local LAN/WLAN" >&2
        printf "%s\n" "==============================================================================================================" >&2
        printf "%s\n" "Necessary:" >&2
        printf "%s\n" "---------" >&2
        printf "%s\n" "--username=<username>                    Username on the server" >&2
        printf "\n" >&2
        printf "%s\n" "Optional:" >&2
        printf "%s\n" "--------" >&2
        printf "%s\n" "--apt-sources-url=<URL>                  URL of latest stable Debian/Ubuntu APT sources" >&2
        printf "%s\n" "                                         By default, it is http://deb.debian.org/debian or http://archive.ubuntu.com/ubuntu" >&2
        printf "%s\n" "--gns3-port=<port_number>                Port number which GNS3 server listens to" >&2
        printf "%s\n" "                                         By default, it is 3080" >&2
        printf "%s\n" "--openvpn-tunnel-ip-address=<ip_address> OpenVPN tunnel IPv4 address on which GNS3 server listens" >&2
        printf "%s\n" "                                         By default, it is 172.31.255.1" >&2
        printf "%s\n" "--repository=<gns3|jc-manciot>           Choose a repository between:" >&2
        printf "%s\n" "                                                 + gns3: official GNS3 repository" >&2
        printf "%s\n" "                                                 + jc-manciot: latest deb packages including GNS3 on the latest stable Debian/Ubuntu" >&2
        printf "%s\n" "                                                   release for x86_64 architectures" >&2
        printf "%s\n" "                                         By default, it is jc-manciot." >&2
        printf "%s\n" "--without-new-apt-sources                Don't install new /etc/apt/sources.list" >&2
        printf "%s\n" "                                         By default, on Debian, the follwoing are installed in /etc/apt/sources.list:" >&2
        printf "%s\n" "                                                 + deb http://deb.debian.org/debian/debian testing main contrib non-free" >&2
        printf "%s\n" "                                                 + deb http://security.debian.org/ testing/updates main contrib non-free" >&2
        printf "%s\n" "                                         By default, on Ubuntu, the follwoing are installed /etc/apt/sources.list:" >&2
        printf "%s\n" "                                                 + deb http://archive.ubuntu.com/ubuntu <os_code_name> main restricted multiverse universe" >&2
        printf "%s\n" "                                                 + deb http://archive.ubuntu.com/ubuntu <os_code_name>-updates main restricted multiverse universe" >&2
        printf "%s\n" "                                                 + deb http://archive.ubuntu.com/ubuntu <os_code_name>-security main restricted multiverse universe" >&2
        printf "%s\n" "--without-openvpn                        Don't install Open VPN; the communications with GNS3 server won't be encrypted" >&2
        printf "%s\n" "                                         By default, an Open VPN is installed & configured." >&2
        printf "%s\n" "--without-openvpn-purge                  Don't purge OpenVPN prior to its reinstallation if it is set to be used" >&2
        printf "%s\n" "                                         By default, openVPN is purged before its installation." >&2
        printf "%s\n" "--without-ufw-gns3-port                  Don't open GNS3 port on UFW firewall." >&2
        printf "%s\n" "                                         By default, UFW is used and GNS3 port is allowed for all sources within or outside" >&2
        printf "%s\n" "                                         OpenVPN tunnel depending on the configuration." >&2
        printf "%s\n" "                                         3080 port and tcp/5000:10000 console ports must be allowed manually somehow on UFW for GNS3 server" >&2
        printf "%s\n" "                                         to be able to connect to its client(s)." >&2
        printf "%s\n" "--without-ufw-openvpn-port               Don't open openvpn port on UFW firewall." >&2
        printf "%s\n" "                                         By default, UFW is used and openVPN port is allowed for all sources." >&2
        printf "%s\n" "                                         udp/1194 port must be allowed manually somehow on UFW for the OpenVPN tunnel to work." >&2
        printf "%s\n" "--without-ufw-ssh-port                   Don't open ssh port on UFW firewall." >&2
        printf "%s\n" "                                         By default, UFW is used and ssh port is allowed for all sources." >&2
        printf "%s\n" "                                         tcp/22 port must be allowed manually somehow on UFW beforehand to be able to:" >&2
        printf "%s\n" "                                                 + keep the current SSH session alive" >&2
        printf "%s\n" "                                                 + retrieve the OpenVPN bundle" >&2
        printf "%s\n" "--without-unstable-repository            Use only JC Manciot's DR/PPA stable repository" >&2
        printf "%s\n" "                                         By default, stable & unstable JC Manciot's DR/PPA are used" >&2
        printf "%s\n" "--help:                                  This help" >&2
}

function report 
{
        printf "%s\n" "______________________________________________________________________________________________________________" >&2
        printf "%s\n" "=> $1" >&2
        printf "%s\n" "==============================================================================================================" >&2
}

function version-ge() { test "$(echo "$@" | tr " " "\n" | sort -uV | head -n 1)" == "$2"; }

if [[ $(whoami) != root ]]; then
        report "This script must be run as root"
        exit 1
fi        

username=""
url_regex='(http[s]*|ftp)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]*[-A-Za-z0-9+&@#/%=~_|]'

repository=jc-manciot
unstable_repository_enabled=true
new_apt_sources_enabled=true

gns3_port=3080
gns3_console_port_range=5000:10000
ufw_gns3_port_enabled=true

openvpn_enabled=true
openvpn_port=1194
openvpn_purge_enabled=true
openvpn_tunnel_ip_address=172.31.255.1
ufw_openvpn_port_enabled=true

ssh_port=22
ufw_ssh_port_enabled=true

# Reading the options
OPTIONS=`getopt -o h --long apt-sources-url:,gns3-port:,openvpn-tunnel-ip-address:,repository:,username:,without-new-apt-sources,without-openvpn,without-openvpn-purge,without-ufw-gns3-port,without-ufw-openvpn-port,without-ufw-ssh-port,without-unstable-repository,help -n 'gns3-install-on-local-server.sh' -- "$@"`
if [ $? -ne 0 ]
then
        help
        exit 1
fi
eval set -- "$OPTIONS"

# Extracting options and their arguments into variables.
while true ; do
        case "$1" in
                --apt-sources-url)
                        case "$2" in
                                "") 
                                        ;;
                                *)
                                        apt_sources_url=$2
                                        ;;
                        esac
                        shift 2
                        ;;
                --gns3-port)
                        case "$2" in
                                "") 
                                        ;;
                                *)
                                        gns3_port=$2
                                        ;;
                        esac
                        shift 2
                        ;;
                --openvpn-tunnel-ip-address)
                        case "$2" in
                                "") 
                                        ;;
                                *)
                                        openvpn_tunnel_ip_address=$2
                                        ;;
                        esac
                        shift 2
                        ;;
                --repository)
                        case "$2" in
                                "") 
                                        ;;
                                *)
                                        repository=$2
                                        ;;
                        esac
                        shift 2
                        ;;
                --username)
                        case "$2" in
                                "") 
                                        ;;
                                *)
                                        username=$2
                                        ;;
                        esac
                        shift 2
                        ;;
                --without-new-apt-sources)
                        new_apt_sources_enabled=false
                        shift
                        ;;
                --without-openvpn)
                        openvpn_enabled=false
                        shift
                        ;;
                --without-openvpn-purge)
                        openvpn_purge_enabled=false
                        shift
                        ;;
                --without-ufw-gns3-port)
                        ufw_gns3_port_enabled=false
                        shift
                        ;;
                --without-ufw-openvpn-port)
                        ufw_openvpn_port_enabled=false
                        shift
                        ;;
                --without-ufw-ssh-port)
                        ufw_ssh_port_enabled=false
                        shift
                        ;;
                --without-unstable-repository)
                        unstable_repository_enabled=false
                        shift
                        ;;
                -h|--help)
                        help
                        exit 1
                        ;;
                --) 
                        shift
                        break
                        ;;
                *)
                        report "Internal error $1"
                        exit 1
                        ;;
        esac
done

if [[ -z $username ]]; then
        report "--username=<username> option is missing"
        exit 1
elif [[ (-n "$apt_sources_url") && (! "$apt_sources_url" =~ $url_regex) ]]; then
        report "$apt_sources_url URL format is not valid"
        exit 1
fi

report "Removing all apt dialogs"
apt install --show-progress --assume-yes debconf-utils
original_frontend_setting=$(debconf-get-selections | grep -P "^debconf[[:blank:]]+debconf/frontend" | awk '{print $4}')
echo 'debconf debconf/frontend select Noninteractive' | debconf-set-selections

os_distribution=$(lsb_release -a  2>/dev/null | grep "Distributor ID" | cut -d ':' -f 2)
os_distribution=${os_distribution//[[:space:]]/}
os_version=$(lsb_release -a  2>/dev/null | grep "Release" | cut -d ':' -f 2)
os_version=${os_version//[[:space:]]/}
os_code_name=$(lsb_release -a  2>/dev/null | grep "Codename" | cut -d ':' -f 2)
os_code_name=${os_code_name//[[:space:]]/}
linux_kernel_version=$(uname -r)
python3_version=$($(which python3) --version | cut -d ' ' -f 2 | sed -E 's|^([0-9]+\.[0-9]+)\..*$|\1|g')
pip3="python${python3_version} -m pip"
case $os_distribution in
        Debian)
                git_repo=DR
                if [[ $os_version =~ testing ]]; then
                        os_version='12.0'
                fi
                if [[ -z "$apt_sources_url" ]]; then
                        apt_sources_url="http://deb.debian.org/debian"
                fi
                case $os_version in
                        12*) # bookworm
                                # Verifying that it is what it says it is
                                if [[ "$linux_kernel_version" < 5.17 ]]; then
                                        echo "Linux kernel version $linux_kernel_version is incompatible with $os_distribution 12.x"
                                        exit 1
                                fi

                                if [[ $new_apt_sources_enabled == true ]]; then
                                        report "Installing new apt sources"
cat <<EOFAPT > /etc/apt/sources.list
deb "$apt_sources_url" testing main contrib non-free
deb-src "$apt_sources_url" testing main contrib non-free
deb http://security.debian.org/ testing/updates main contrib non-free
deb-src http://security.debian.org/ testing/updates main contrib non-free
EOFAPT
                                fi

                                report "Updating system deb packages list"
                                apt update

                                report "Installing primary package"
                                apt install --show-progress --assume-yes apt-transport-https

                                case $repository in
                                        gns3)
                                                report "Installing GNS3 PPA"
                                                apt install --show-progress --assume-yes software-properties-common
                                                add-apt-repository ppa:gns3/ppa
                                                ;;
                                        jc-manciot)
                                                report "Adding JC Manciot's Public GPG key"
                                                if [[ -z $(gpg --list-keys | grep DF7396D82BBA3684FCCADD4DB063838ED13997FD) ]]; then
                                                        return_code_file="/root/.DF7396D82BBA3684FCCADD4DB063838ED13997FD"
                                                        for key_server in keyserver.ubuntu.com keys.openpgp.org keys.gnupg.net
                                                        do
                                                                output=$(gpg --keyserver $key_server --keyserver-options timeout=40 --receive-keys DF7396D82BBA3684FCCADD4DB063838ED13997FD 2>&1; echo $? > "${return_code_file}")
                                                                return_code=$(cat "${return_code_file}")
                                                                rm -f "${return_code_file}"
                                                                if [[ ($return_code -eq 0) && (-n $(printf "%s\n" "${output[@]}" | grep -P "gpg: key .* imported")) ]]; then
                                                                        break
                                                                fi
                                                        done
                                                fi
                                                if [[ -z $(apt-key list 2>/dev/null | grep "DF73 96D8 2BBA 3684 FCCA  DD4D B063 838E D139 97FD") ]]; then
                                                        gpg --export --armor DF7396D82BBA3684FCCADD4DB063838ED13997FD > "/etc/apt/trusted.gpg.d/JC_Manciot_DR.asc"
                                                fi

                                                report "Adding stable JC Manciot's ${git_repo}"
                                                echo "deb https://git.sdxlive.com/${git_repo}/plain/Debian ${os_code_name} stable #JC Manciot ${git_repo}" > /etc/apt/sources.list.d/jean-christophe-manciot.list
                                                #"

                                                if [[ $unstable_repository_enabled == true ]]; then
                                                        report "Adding unstable JC Manciot's ${git_repo}"
                                                        echo "deb https://git.sdxlive.com/${git_repo}/plain/Debian ${os_code_name} unstable #JC Manciot ${git_repo}" >> /etc/apt/sources.list.d/jean-christophe-manciot.list
                                                        #"
                                                fi
                                                ;;
                                        *)
                                                report "$repository is not supported"
                                                exit 1
                                                ;;
                                esac
                                ;;
                        *)
                                report "Current OS/version is not supported:"
                                printf "%s\n" "Detected OS $os_distribution"
                                printf "%s\n" "Detected OS version $os_version"
                                printf "%s\n" "Detected OS code name $os_code_name"
                                report "Only the latest stable Debian release is supported"
                                exit 1
                                ;;
                esac
                ;;
        *buntu)
                git_repo=PPA
                if [[ -z "$apt_sources_url" ]]; then
                        apt_sources_url="http://archive.ubuntu.com/ubuntu/"
                fi
                case $os_version in
                        '23.04') # lunar
                                # Verifying that it is what it says it is
                                if [[ "$linux_kernel_version" < 6.2 ]]; then
                                        echo "Linux kernel version $linux_kernel_version is incompatible with $os_distribution $os_version"
                                        exit 1
                                fi
                                if [[ $new_apt_sources_enabled == true ]]; then
                                        report "Installing new apt sources"
cat <<EOFAPT > /etc/apt/sources.list
deb "$apt_sources_url" ${os_code_name} main restricted multiverse universe
deb-src "$apt_sources_url" ${os_code_name} main restricted multiverse universe
deb "$apt_sources_url" ${os_code_name}-updates main restricted multiverse universe
deb-src "$apt_sources_url" ${os_code_name}-updates main restricted multiverse universe
deb "$apt_sources_url" ${os_code_name}-security main restricted multiverse universe
deb-src "$apt_sources_url" ${os_code_name}-security main restricted multiverse universe
EOFAPT
                                fi

                                report "Updating system deb packages list"
                                apt update

                                report "Installing primary package"
                                apt install --show-progress --assume-yes apt-transport-https

                                case $repository in
                                        gns3)
                                                report "Installing GNS3 PPA"
                                                apt install --show-progress --assume-yes software-properties-common
                                                add-apt-repository ppa:gns3/ppa
                                                ;;
                                        jc-manciot)
                                                report "Adding JC Manciot's Public GPG key"
                                                if [[ -z $(gpg --list-keys | grep DF7396D82BBA3684FCCADD4DB063838ED13997FD) ]]; then
                                                        return_code_file="/root/.DF7396D82BBA3684FCCADD4DB063838ED13997FD"
                                                        for key_server in keyserver.ubuntu.com keys.openpgp.org keys.gnupg.net
                                                        do
                                                                output=$(gpg --keyserver $key_server --keyserver-options timeout=40 --receive-keys DF7396D82BBA3684FCCADD4DB063838ED13997FD 2>&1; echo $? > "${return_code_file}")
                                                                return_code=$(cat "${return_code_file}")
                                                                rm -f "${return_code_file}"
                                                                if [[ ($return_code -eq 0) && (-n $(printf "%s\n" "${output[@]}" | grep -P "gpg: key .* imported")) ]]; then
                                                                        break
                                                                fi
                                                        done
                                                fi
                                                if [[ -z $(apt-key list 2>/dev/null | grep "DF73 96D8 2BBA 3684 FCCA  DD4D B063 838E D139 97FD") ]]; then
                                                        gpg --export --armor DF7396D82BBA3684FCCADD4DB063838ED13997FD > "/etc/apt/trusted.gpg.d/JC_Manciot_PPA.asc"
                                                fi

                                                report "Adding stable JC Manciot's ${git_repo}"
                                                echo "deb https://git.sdxlive.com/${git_repo}/plain/Ubuntu ${os_code_name} stable #JC Manciot Stable ${git_repo}" > /etc/apt/sources.list.d/jean-christophe-manciot.list

                                                if [[ $unstable_repository_enabled == true ]]; then
                                                        report "Adding unstable JC Manciot's ${git_repo}"
                                                        echo "deb https://git.sdxlive.com/${git_repo}/plain/Ubuntu ${os_code_name} unstable #JC Manciot Unstable ${git_repo}" >> /etc/apt/sources.list.d/jean-christophe-manciot.list
                                                fi
                                                ;;
                                        *)
                                                report "$repository is not supported"
                                                exit 1
                                                ;;
                                esac
                                ;;
                        *)
                                report "Current OS/version is not supported:"
                                printf "%s\n" "Detected OS $os_distribution"
                                printf "%s\n" "Detected OS version $os_version"
                                printf "%s\n" "Detected OS code name $os_code_name"
                                report "Only the latest Ubuntu release is supported"
                                exit 1
                                ;;
                esac
                ;;
        *)
                report "Current OS/version is not supported:"
                printf "%s\n" "Detected OS $os_distribution"
                printf "%s\n" "Detected OS version $os_version"
                printf "%s\n" "Detected OS code name $os_code_name"
                report "Only the latest Ubuntu release is supported"
                exit 1
                ;;
esac

report "Updating system deb packages list"
apt update

report "Upgrading deb packages"
apt upgrade --yes --allow-downgrades -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold"

report "Installing, enabling & starting UFW firewall"
apt install --show-progress --assume-yes --allow-downgrades ufw
if [[ $ufw_ssh_port_enabled == true ]]; then
        report "Allowing SSH on UFW firewall for all sources"
        ufw allow ${ssh_port}/tcp
else
        ufw_ssh_port_v4_rule_number=$(ufw status numbered | grep -E "^[[:blank:]]*\[[[:blank:]0-9]+\][[:blank:]]*${ssh_port}/tcp[[:blank:]]*ALLOW" | sed -E 's|^[[:blank:]]*\[[[:blank:]]*([0-9]+)\].*$|\1|g')
        if [[ $ufw_ssh_port_v4_rule_number -ne 0 ]]; then
                ufw --force delete $ufw_ssh_port_v4_rule_number
        fi
        ufw_ssh_port_v6_rule_number=$(ufw status numbered | grep -E "^[[:blank:]]*\[[[:blank:]0-9]+\][[:blank:]]*${ssh_port}/tcp[[:blank:]]*\(v6\)[[:blank:]]*ALLOW" | sed -E 's|^[[:blank:]]*\[[[:blank:]]*([0-9]+)\].*$|\1|g')
        if [[ $ufw_ssh_port_v6_rule_number -ne 0 ]]; then
                ufw --force delete $ufw_ssh_port_v6_rule_number
        fi
fi

systemctl enable ufw
systemctl start ufw
return_code=$?
if [[ $return_code -ne 0 ]]; then
        report "Could not start UFW Firewall service"
        report "Consult /var/log/ufw.log"
        systemctl --no-pager --full status ufw
        exit $return_code      
fi

report "Listing UFW Firewall rules"
ufw status verbose

report "Installing some utilities"
apt install --show-progress --assume-yes --allow-downgrades coreutils cpu-checker cpulimit dynamips geoip-bin grep iproute2 kmod libc-bin libexpat1 libsystemd-dev libvirt-daemon-system net-tools ovmf passwd python3-async-generator python3-virtualenv qemu-system-x86 qemu-utils sed systemd zlib1g

report "Configuring nested KVM"
echo "options kvm_intel nested=1" > /etc/modprobe.d/qemu-system-x86.conf

# "Making sure /etc/modprobe.d/* files are read"
if [[ $(lsmod | grep "kvm_intel") =~ ^kvm_intel ]]; then
        rmmod kvm_intel
fi
if [[ $(lsmod | grep "kvm ") =~ ^kvm ]]; then
        rmmod kvm
fi
getent group kvm || groupadd kvm
modprobe kvm
modprobe kvm_intel
chown --no-dereference root:kvm /dev/kvm

report "Setting SUID for all /usr/bin/qemu-* binaries"
chmod u+s /usr/bin/qemu-*

if [[ -z $(kvm-ok | grep "KVM acceleration can be used") ]]; then
        report "KVM acceleration cannot be used: exiting"
        exit 1
elif [[ (-e /sys/module/kvm_intel/parameters/nested) && (($(cat /sys/module/kvm_intel/parameters/nested) -eq 1) || ($(cat /sys/module/kvm_intel/parameters/nested | grep Y) == Y)) ]]; then
        vCPUs=$(grep -cE '(vmx|svm)' /proc/cpuinfo)
        report "Nested KVM acceleration can be used on $vCPUs Intel vCPUs"
        apt install --show-progress --assume-yes --allow-downgrades intel-microcode
elif [[ (-e /sys/module/kvm_amd/parameters/nested) && (($(cat /sys/module/kvm_amd/parameters/nested) -eq 1) || ($(cat /sys/module/kvm_amd/parameters/nested | grep Y) == Y)) ]]; then
        vCPUs=$(grep -cE '(vmx|svm)' /proc/cpuinfo)
        report "Nested KVM acceleration can be used on $vCPUs AMD vCPUs"
        apt install --show-progress --assume-yes --allow-downgrades amd64-microcode
else
        report "Nested KVM acceleration cannot be used: exiting"
        exit 1
fi

id -u ${username}
if [[ $? -eq 1 ]]; then
        report "Creating user ${username}"
        useradd -m ${username}
fi

report "Creating group ubridge"
getent group ubridge || groupadd ubridge

report "Adding ${username} to the ubridge group"
usermod -aG ubridge ${username}

report "Adding ${username} to the kvm group"
usermod -aG kvm ${username}

report "Detecting the server LAN IP address"
default_interface=$(ip route show | grep default  | head -n 1 | cut -d ' ' -f 5)
server_lan_ip_address=$(ifconfig $default_interface | grep "inet " | sed 's|^.* inet \(.*\) netmask .*|\1|g')
# Removing all spaces, tabs, line breaks
server_lan_ip_address=${server_lan_ip_address//[[:space:]]/}
echo "$server_lan_ip_address"

report "Installing GNS3 Server inside a virtual environment in /opt/gns3/venv"
apt purge -y gns3-server
rm -rf /opt/gns3
mkdir -pv /opt/gns3
chown root:root /opt/gns3
cd /opt/gns3
python3_bin_path=/usr/bin
python3_version=$(${python3_bin_path}/python3 --version | cut -d ' ' -f 2 | sed -E 's|^([0-9]+\.[0-9]+)\..*$|\1|g')
virtualenv -p /usr/bin/python${python3_version} --always-copy --download --verbose venv

python3_bin_path=/opt/gns3/venv/bin
pip3="${python3_bin_path}/python${python3_version} -m pip"

#-------------Running inside Python virtual env: /opt/gns3/venv---
. ${python3_bin_path}/activate
$pip3 install -I -U gns3-server
gns3_version=$($pip3 show gns3-server | grep ^Version | sed -E 's|^Version: ([0-9]+\.[0-9]+).*$|\1|g')
deactivate
#-------------Running outside Python virtual env: /opt/gns3/venv---

report "Setting up GNS3 folders"
if [[ ! (-d /var/log/gns3) ]]; then
        mkdir -pv /var/log/gns3
fi
if [[ ! (-d /run/gns3) ]]; then
        mkdir -pv /run/gns3
fi
if [[ ! (-d /home/${username}/GNS3/Images) ]]; then
        mkdir -pv /home/${username}/GNS3/Images
fi
if [[ ! (-d /home/${username}/GNS3/Labs) ]]; then
        mkdir -pv /home/${username}/GNS3/Labs
fi
if [[ ! (-d /root/.config/GNS3) ]]; then
        mkdir -pv /root/.config/GNS3/${gns3_version}
fi
chown --no-dereference -R ${username}: /home/${username}/GNS3
chmod -R 700 /home/${username}/GNS3

report "Setting up GNS3 server"
if [[ ! (-e /root/.config/GNS3/${gns3_version}/gns3_server.conf) ]]; then
cat <<EOFC > /root/.config/GNS3/${gns3_version}/gns3_server.conf
[Server]
host = $server_lan_ip_address
port = $gns3_port 
appliances_path = /home/${username}/GNS3/Images
configs_path = /home/${username}/GNS3/configs
images_path = /home/${username}/GNS3/Images
path = ${python3_bin_path}/gns3server
projects_path = /home/${username}/GNS3/Labs
protocol = http
report_errors = True
symbols_path = /home/${username}/GNS3/symbols

[Qemu]
enable_kvm = True
EOFC
else
        sed --follow-symlinks -Ei "s|^host[[:blank:]]*=.*|host = ${server_lan_ip_address}|g" /root/.config/GNS3/${gns3_version}/gns3_server.conf
        sed --follow-symlinks -Ei "s|^port[[:blank:]]*=.*|port = ${gns3_port}|g" /root/.config/GNS3/${gns3_version}/gns3_server.conf
        sed --follow-symlinks -Ei "s|^appliances_path[[:blank:]]*=.*|appliances_path = /home/${username}/GNS3/Images|g" /root/.config/GNS3/${gns3_version}/gns3_server.conf
        sed --follow-symlinks -Ei "s|^configs_path[[:blank:]]*=.*|configs_path = /home/${username}/GNS3/configs|g" /root/.config/GNS3/${gns3_version}/gns3_server.conf
        sed --follow-symlinks -Ei "s|^images_path[[:blank:]]*=.*|images_path = /home/${username}/GNS3/Images|g" /root/.config/GNS3/${gns3_version}/gns3_server.conf
        sed --follow-symlinks -Ei "s|^path[[:blank:]]*=.*|path = ${python3_bin_path}/gns3server|g" /root/.config/GNS3/${gns3_version}/gns3_server.conf
        sed --follow-symlinks -Ei "s|^projects_path[[:blank:]]*=.*|projects_path = /home/${username}/GNS3/Labs|g" /root/.config/GNS3/${gns3_version}/gns3_server.conf
        sed --follow-symlinks -Ei "s|^protocol[[:blank:]]*=.*|protocol = ${protocol}|g" /root/.config/GNS3/${gns3_version}/gns3_server.conf
        sed --follow-symlinks -Ei "s|^report_errors[[:blank:]]*=.*|report_errors = True|g" /root/.config/GNS3/${gns3_version}/gns3_server.conf
        sed --follow-symlinks -Ei "s|^symbols_path[[:blank:]]*=.*|symbols_path = /home/${username}/GNS3/symbols|g" /root/.config/GNS3/${gns3_version}/gns3_server.conf
        sed --follow-symlinks -Ei "s|^enable_kvm[[:blank:]]*=.*|enable_kvm = True|g" /root/.config/GNS3/${gns3_version}/gns3_server.conf
fi

report "Starting GNS3 as a daemon"
if [[ -n $(ps -elf | grep gns3server  | grep -v grep) ]]; then
        kill $(ps -elf | grep gns3server | grep -v grep | awk '{print $4}')
fi
#-------------Running inside Python virtual env: /opt/gns3/venv---
. ${python3_bin_path}/activate
gns3server --log /var/log/gns3/gns3.log --daemon
return_code=$?
if [[ $return_code -eq 0 ]]; then
        report "GNS3 installed and started with success"
else 
        report "Could not start GNS3 daemon; try . ${python3_bin_path}/activate; ${python3_bin_path}/gns3server --debug; deactivate and please report the issue to support@sdxlive.com"
        deactivate
        exit $return_code      
fi
deactivate
#-------------Running outside Python virtual env: /opt/gns3/venv---

if [[ $ufw_gns3_port_enabled == true ]]; then
        report "Opening GNS3 server port on UFW firewall"
        ufw allow ${gns3_port}
        ufw allow ${gns3_console_port_range}/tcp
else
        ufw_gns3_port_v4_rule_number=$(ufw status numbered | grep -E "^[[:blank:]]*\[[[:blank:]0-9]+\][[:blank:]]*${gns3_port}[[:blank:]]*ALLOW" | sed -E 's|^[[:blank:]]*\[[[:blank:]]*([0-9]+)\].*$|\1|g')
        if [[ $ufw_gns3_port_v4_rule_number -ne 0 ]]; then
                ufw --force delete $ufw_gns3_port_v4_rule_number
        fi
        ufw_gns3_port_v6_rule_number=$(ufw status numbered | grep -E "^[[:blank:]]*\[[[:blank:]0-9]+\][[:blank:]]*${gns3_port}[[:blank:]]*\(v6\)[[:blank:]]*ALLOW" | sed -E 's|^[[:blank:]]*\[[[:blank:]]*([0-9]+)\].*$|\1|g')
        if [[ $ufw_gns3_port_v6_rule_number -ne 0 ]]; then
                ufw --force delete $ufw_gns3_port_v6_rule_number
        fi
        ufw_gns3_port_range_v4_rule_number=$(ufw status numbered | grep -E "^[[:blank:]]*\[[[:blank:]0-9]+\][[:blank:]]*${gns3_console_port_range}/tcp[[:blank:]]*ALLOW" | sed -E 's|^[[:blank:]]*\[[[:blank:]]*([0-9]+)\].*$|\1|g')
        if [[ $ufw_gns3_port_range_v4_rule_number -ne 0 ]]; then
                ufw --force delete $ufw_gns3_port_range_v4_rule_number
        fi
        ufw_gns3_port_range_v6_rule_number=$(ufw status numbered | grep -E "^[[:blank:]]*\[[[:blank:]0-9]+\][[:blank:]]*${gns3_console_port_range}/tcp[[:blank:]]*\(v6\)[[:blank:]]*ALLOW" | sed -E 's|^[[:blank:]]*\[[[:blank:]]*([0-9]+)\].*$|\1|g')
        if [[ $ufw_gns3_port_range_v6_rule_number -ne 0 ]]; then
                ufw --force delete $ufw_gns3_port_range_v6_rule_number
        fi
fi

report "Restarting UFW Firewall service"
systemctl restart ufw
return_code=$?
if [[ $return_code -ne 0 ]]; then
        report "Could not restart UFW Firewall service"
        report "Consult /var/log/ufw.log"
        systemctl --no-pager --full status ufw
        exit $return_code      
fi

if [[ $openvpn_enabled == true ]]; then
        if [[ $openvpn_purge_enabled == true ]]; then
                report "Purging potential previous OpenVPN Easy-RSA"
                if [[ $(systemctl is-active openvpn) == active ]]; then
                        systemctl stop openvpn
                fi
                dpkg --get-selections | grep -q "^openvpn[[:space:]]*install$"
                if [[ $? -eq 0 ]]; then
                        apt purge --show-progress --assume-yes easy-rsa openvpn
                        rm -rfv /etc/easy-rsa
                        rm -rfv /etc/openvpn
                        rm -fv /var/log/openvpn.log
                fi
        fi

        report "Installing packages for OpenVPN"
        # Easy-rsa is incompatible with openssl 3.x
        openssl_version_for_easy_rsa=$(apt-cache policy openssl | grep -P "^[[:blank:]*]+1\.[0-9]+.*$" | sed -E 's|\*| |g' | sort -rV | head -n 1 | awk '{print $1}')
        if [[ -z $openssl_version_for_easy_rsa ]]; then
                report "There is no version of openssl 1.x compatible with easy-rsa"
                exit 1
        fi
        apt install --reinstall --show-progress --assume-yes --allow-downgrades --allow-change-held-packages dnsutils easy-rsa openssl=${openssl_version_for_easy_rsa} openvpn whois
        apt-mark hold openssl

        report "Setting up OpenVPN"
        [[ -d /dev/net ]] || mkdir -p /dev/net
        [[ -c /dev/net/tun ]] || mknod /dev/net/tun c 10 200

        server_hostname=$(hostname --fqdn)
        server_wan_ip_address=$(dig @ns1.google.com -t txt o-o.myaddr.l.google.com +short | sed 's/"//g')
        server_country=$(geoiplookup ${server_wan_ip_address} | cut -d ':' -f 2 | sed -E 's|^[[:blank:]]*([^[:blank:]]+),.*$|\1|g')

        report "My detected hostname:           $server_hostname"
        report "My detected LAN IPv4 address:   $server_lan_ip_address"
        report "My detected WAN IPv4 address:   $server_wan_ip_address"
        report "My detected country:            $server_country"

        report "Creating OpenVPN server configuration"
        # Example VPN server configuration
        if [[ -e /usr/share/doc/openvpn/examples/sample-config-files/server.conf.gz ]]; then
                gunzip -c /usr/share/doc/openvpn/examples/sample-config-files/server.conf.gz > /etc/openvpn/server.conf
        elif [[ -e /usr/share/doc/openvpn/examples/sample-config-files/server.conf ]]; then
                cp -fv /usr/share/doc/openvpn/examples/sample-config-files/server.conf /etc/openvpn/server.conf
        else
                report "Could not locate server.conf below /usr/share/doc/openvpn/examples/sample-config-files"
                exit 1
        fi
        # Listening on our IP address
        sed --follow-symlinks -Ei "s|^[[:blank:];#]*local .*$|local $server_lan_ip_address|g" /etc/openvpn/server.conf
        # Setting our IP address
        openvpn_tunnel_subnet_ip_address=$(echo "$openvpn_tunnel_ip_address" | sed -E 's|^(.+)\.[0-9]+$|\1|g').0
        sed --follow-symlinks -Ei "s|^[[:blank:];#]*server .*$|server ${openvpn_tunnel_subnet_ip_address} 255.255.255.0|g" /etc/openvpn/server.conf
        # Setting a routed IP tunnel
        sed --follow-symlinks -Ei "s|^[[:blank:];#]*(dev tun).*$|\1|g" /etc/openvpn/server.conf
        if [[ -n $(grep -P "^[[:blank:];#]*(dev tap.*)$" /etc/openvpn/server.conf) ]]; then
                # Commenting out the ethernet tunnel
                sed --follow-symlinks -Ei "s|^[[:blank:];#]*(dev tap.*)$|;\1|g" /etc/openvpn/server.conf
        fi
        # Setting CA certificate
        sed --follow-symlinks -Ei "s|^[[:blank:];#]*ca .*$|ca server/ca.crt|g" /etc/openvpn/server.conf
        # Setting server certificate
        sed --follow-symlinks -Ei "s|^[[:blank:];#]*cert .*$|cert server/${server_hostname}.crt|g" /etc/openvpn/server.conf
        # Setting server key
        sed --follow-symlinks -Ei "s|^[[:blank:];#]*key .*$|key server/${server_hostname}.key|g" /etc/openvpn/server.conf
        # Setting cipher
        sed --follow-symlinks -Ei "s|^[[:blank:];#]*cipher .*$|cipher AES-256-GCM|g" /etc/openvpn/server.conf
        # Setting HMAC message digest algorithm 
        sed --follow-symlinks -Ei "s|^[[:blank:];#]*auth .*$|auth SHA256|g" /etc/openvpn/server.conf
        # Setting Diffie-Hellman as none
        sed --follow-symlinks -Ei "s|^[[:blank:];#]*dh .*$|dh none|g" /etc/openvpn/server.conf
        if [[ -n $(grep -P "^[[:blank:];#]*(tls-auth .*)$" /etc/openvpn/server.conf) ]]; then
                # Commenting out tls-auth
                sed --follow-symlinks -Ei "s|^[[:blank:];#]*(tls-auth .*)$|;\1|g" /etc/openvpn/server.conf
        fi
        if [[ -n $(grep -P "^[[:blank:];#]*(key-direction .*)$" /etc/openvpn/server.conf) ]]; then
                # Commenting out key-direction
                sed --follow-symlinks -Ei "s|^[[:blank:];#]*(key-direction .*)$|;\1|g" /etc/openvpn/server.conf
        fi
        # Allowing older compression
        # sed --follow-symlinks -i 's|^;comp-lzo|comp-lzo|g' /etc/openvpn/server.conf
        # Reducing dead timer from 2 mns to 1 mn
        sed --follow-symlinks -Ei 's|^[[:blank:];#]*keepalive .*$|keepalive 10 60|g' /etc/openvpn/server.conf
        # Logging file
        sed --follow-symlinks -Ei 's|^[[:blank:];#]*log-append .*$|log-append /var/log/openvpn.log|g' /etc/openvpn/server.conf
        # Setting up a local management interface which can be accessed with 'telnet 127.0.0.1 1195'
        printf "\n%s\n%s\n" "# Setting up a local management interface which can be accessed with 'telnet 127.0.0.1 1195'" "management 127.0.0.1 1195" >> /etc/openvpn/server.conf

        report "Creating an Easy-RSA PKI"
        # Copying over the Easy-RSA generation scripts
        cp -frv /usr/share/easy-rsa/ /etc
        cd /etc/easy-rsa
        mv vars.example vars
        # Setting all the variables for our certificate
        export EASYRSA_BATCH='batch'
        export EASYRSA_DN='cn_only'
        export EASYRSA_REQ_CN="${server_hostname}"
        export EASYRSA_ALGO='ec'
        export EASYRSA_CURVE='secp521r1'
        export EASYRSA_DIGEST='sha512'
        export EASYRSA_NS_SUPPORT='yes'
        ./easyrsa init-pki
        
        report "Generating the Certificate Authority"
        ./easyrsa build-ca nopass
        
        find -name ca.crt -exec cp -fv {} /etc/openvpn/server \;
        chown --no-dereference root:root /etc/openvpn/server/ca.crt
        chmod 640 /etc/openvpn/server/ca.crt

        report "Generating the Certificate and Key for the Server"
        # Making a certificate/private key pair using a locally generated root certificate.
        # This will designate the certificate as a server-only certificate by setting the right attributes.
        ./easyrsa gen-req "${server_hostname}" nopass
        
        cp -fv /etc/easy-rsa/pki/private/${server_hostname}.key /etc/openvpn/server/${server_hostname}.key
        chown root:root /etc/openvpn/server/${server_hostname}.key
        chmod 640 /etc/openvpn/server/${server_hostname}.key

        report "Generating the Certificate and Key for the client"
        ./easyrsa gen-req client1 nopass
        
        cp -fv /etc/easy-rsa/pki/private/client1.key /etc/openvpn/client/
        chown root:root /etc/openvpn/client/client1.key
        chmod 640 /etc/openvpn/client/client1.key

        report "Signing the server certificate"
        ./easyrsa show-req ${server_hostname}
        ./easyrsa sign-req server ${server_hostname}

        cp -fv /etc/easy-rsa/pki/issued/${server_hostname}.crt /etc/openvpn/server/${server_hostname}.crt
        chown root:root /etc/openvpn/server/${server_hostname}.crt
        chmod 640 /etc/openvpn/server/${server_hostname}.crt
        
        report "Signing the client certificate"
        ./easyrsa show-req client1
        ./easyrsa sign-req client client1
        
        cp -fv /etc/easy-rsa/pki/issued/client1.crt /etc/openvpn/client
        chown root:root /etc/openvpn/client/client1.crt
        chmod 640 /etc/openvpn/client/client1.crt
        
        report "Generating the client ovpn file into:"
        report "/etc/openvpn/client/openvpn@${server_hostname}.ovpn"
        ./openvpn-gen.sh "$server_hostname" /etc/openvpn/server/ca.crt /etc/openvpn/client/client1.crt /etc/openvpn/client/client1.key > "/etc/openvpn/client/openvpn@${server_hostname}.ovpn"

        report "Allowing IPv4 Forwarding"
        sed --follow-symlinks -i 's|^.*DEFAULT_FORWARD_POLICY=".*"|DEFAULT_FORWARD_POLICY="ACCEPT"|g' /etc/default/ufw
        sed --follow-symlinks -i "s|^.*net.ipv4.ip_forward=.*|net.ipv4.ip_forward=1|g" /etc/sysctl.conf
        sysctl -p

        report "Adjusting the UFW Firewall Rules to Masquerade Client Connections"
        if [[ -z $(cat /etc/ufw/before.rules | grep -- "^-A POSTROUTING -s ${openvpn_tunnel_subnet_ip_address}/24 -o ${default_interface} -j MASQUERADE") ]]; then
                sed --follow-symlinks -i "s|^# Don't delete these required lines, otherwise there will be errors|# START OPENVPN RULES\n# NAT table rules\n*nat\n:POSTROUTING ACCEPT [0:0]\n# Allow traffic from OpenVPN client to default interface\n-A POSTROUTING -s ${openvpn_tunnel_subnet_ip_address}/24 -o ${default_interface} -j MASQUERADE\nCOMMIT\n# END OPENVPN RULES\n\n# Don't delete these required lines, otherwise there will be errors|g" /etc/ufw/before.rules
        fi

        report "Restarting OpenVPN Server service"
        systemctl enable openvpn@server
        systemctl restart openvpn@server
        return_code=$?
        if [[ $return_code -ne 0 ]]; then
                report "Could not restart OpenVPN server service"
                report "Consult /var/log/openvpn.log"
                systemctl --no-pager --full status openvpn@server
                exit $return_code      
        fi
        
        if [[ $ufw_openvpn_port_enabled == true ]]; then
                report "Opening OpenVPN port on UFW firewall"
                ufw allow ${openvpn_port}/udp
        else
                ufw_openvpn_port_v4_rule_number=$(ufw status numbered | grep -E "^[[:blank:]]*\[[[:blank:]0-9]+\][[:blank:]]*${openvpn_port}/(udp|tcp)[[:blank:]]*ALLOW" | sed -E 's|^[[:blank:]]*\[[[:blank:]]*([0-9]+)\].*$|\1|g')
                if [[ $ufw_openvpn_port_v4_rule_number -ne 0 ]]; then
                        ufw --force delete $ufw_openvpn_port_v4_rule_number
                fi
                ufw_openvpn_port_v6_rule_number=$(ufw status numbered | grep -E "^[[:blank:]]*\[[[:blank:]0-9]+\][[:blank:]]*${openvpn_port}/(udp|tcp)[[:blank:]]*\(v6\)[[:blank:]]*ALLOW" | sed -E 's|^[[:blank:]]*\[[[:blank:]]*([0-9]+)\].*$|\1|g')
                if [[ $ufw_openvpn_port_v6_rule_number -ne 0 ]]; then
                        ufw --force delete $ufw_openvpn_port_v6_rule_number
                fi
        fi

        report "Making GNS3 Server listen inside the OpenVPN Tunnel"
        sed --follow-symlinks -i "s|host[[:blank:]]*=.*|host = ${openvpn_tunnel_ip_address}|g" /root/.config/GNS3/${gns3_version}/gns3_server.conf

        report "Updating UFW Firewall Rules for OpenVPN & GNS3"
        ufw_gns3_port_v4_rule_number=$(ufw status numbered | grep -E "^[[:blank:]]*\[[[:blank:]0-9]+\][[:blank:]]*${gns3_port}[[:blank:]]*ALLOW" | sed -E 's|^[[:blank:]]*\[[[:blank:]]*([0-9]+)\].*$|\1|g')
        if [[ $ufw_gns3_port_v4_rule_number -ne 0 ]]; then
                ufw --force delete $ufw_gns3_port_v4_rule_number
        fi
        ufw_gns3_port_v6_rule_number=$(ufw status numbered | grep -E "^[[:blank:]]*\[[[:blank:]0-9]+\][[:blank:]]*${gns3_port}[[:blank:]]*\(v6\)[[:blank:]]*ALLOW" | sed -E 's|^[[:blank:]]*\[[[:blank:]]*([0-9]+)\].*$|\1|g')
        if [[ $ufw_gns3_port_v6_rule_number -ne 0 ]]; then
                ufw --force delete $ufw_gns3_port_v6_rule_number
        fi
        ufw allow in to ${openvpn_tunnel_ip_address} port ${gns3_port}
        # In case all out are denied on pre-existing UFW configuration
        ufw allow out from ${openvpn_tunnel_ip_address}
        
        report "Restarting GNS3 daemon"
        kill $(ps -elf | grep gns3server | grep -v grep | awk '{print $4}')
        #-------------Running inside Python virtual env: /opt/gns3/venv---
        . ${python3_bin_path}/activate
        gns3server --log /var/log/gns3/gns3.log --daemon
        return_code=$?
        if [[ $return_code -eq 0 ]]; then
                report "GNS3 installed and started with success inside the tunnel"
        else 
                report "Could not restart GNS3 daemon inside the tunnel; try . ${python3_bin_path}/activate; ${python3_bin_path}/gns3server --debug; deactivate and please report the issue to support@sdxlive.com"
                exit $return_code      
        fi
        deactivate
        #-------------Running outside Python virtual env: /opt/gns3/venv---

        report "Restarting UFW Firewall service"
        systemctl restart ufw
        return_code=$?
        if [[ $return_code -ne 0 ]]; then
                report "Could not restart UFW Firewall service"
                report "Consult /var/log/ufw.log"
                systemctl --no-pager --full status ufw
                exit $return_code      
        fi
        
        report "Updating MOTD"
        gns3_user=$(cat /root/.config/GNS3/${gns3_version}/gns3_server.conf | grep -P "^[[:blank:]]*user[[:blank:]]*=[[:blank:]]*([^[:blank:]]+).*$" | sed -E 's|^[[:blank:]]*user[[:blank:]]*=[[:blank:]]*([^[:blank:]]+).*$|\1|g')
        gns3_password=$(cat /root/.config/GNS3/${gns3_version}/gns3_server.conf | grep -P "^[[:blank:]]*password[[:blank:]]*=[[:blank:]]*([^[:blank:]]+).*$" | sed -E 's|^[[:blank:]]*password[[:blank:]]*=[[:blank:]]*([^[:blank:]]+).*$|\1|g')
        if [[ $openvpn_enabled == true ]]; then
# The following cannot be prepended with spaces
cat <<EOFMOTD > /etc/update-motd.d/70-openvpn
#!/bin/sh
printf "%s\n" "__________________________________________________________________________________________________________"
printf "%s\n" "Inside the client terminal:"
printf "%s\n" "---------------------------"
printf "%s\n" "Download the OpenVPN client config file with:"
printf "%s\n" "scp root@${server_wan_ip_address}:/etc/openvpn/client/openvpn\@${server_hostname}.ovpn /etc/openvpn/client"
printf "\n"
printf "%s\n" "Import the OpenVPN client config file to Network Manager with:"
printf "%s\n" "nmcli connection import type openvpn file /etc/openvpn/client/openvpn\@${server_hostname}.ovpn"
printf "\n"
printf "%s\n" "Open the OpenVPN tunnel with:"
printf "%s\n" "nmcli con up id openvpn\@${server_hostname}"
printf "\n"
printf "%s\n" "Inside the client GNS3:"
printf "%s\n" "-----------------------"
printf "%s\n" "Once the OpenVPN tunnel has been correctly setup, you should be able to define a node on the remote server"
printf "%s\n" "Defining the remote server:"
printf "%s\n" "Edit Preferences -> Server -> Remote Servers -> Add -> ${protocol} - ${openvpn_tunnel_ip_address} - ${gns3_port}"
printf "%s\n" "Edit Preferences -> Server -> Remote Servers -> Add -> enable authentication - User: ${gns3_user}"
printf "%s\n" "Edit Preferences -> Server -> Remote Servers -> Add -> enable authentication - Password: ${gns3_password}"
printf "%s\n" "Edit Preferences -> Server -> Remote Servers -> Add -> enable authentication -> OK"
printf "\n"
printf "%s\n" "Defining the remote node:"
printf "%s\n" "Edit Preferences -> Qemu VMs -> New -> Run this Qemu VM on a remote computer -> Run on <remote_server_name> -> Next -> Name -> Next"
printf "%s\n" "If the connection is successful, the Qemu binary name is retrieved"
printf "\n"
printf "%s\n" "Inside the server terminal:"
printf "%s\n" "---------------------------"
printf "%s\n" "Purge this MOTD with:"
printf "%s\n" "sudo rm -fv /etc/update-motd.d/70-openvpn"
printf "\n"
printf "%s\n" "At each boot of your server:"
printf "%s\n" "---------------------------"
printf "%s\n" "It is necessary to start GNS3 daemon with:"
printf "%s\n" ". ${python3_bin_path}/activate"
printf "%s\n" "gns3server --log /var/log/gns3/gns3.log --daemon"
printf "%s\n" "deactivate"
printf "\n"
printf "%s\n" "=========================================================================================================="
EOFMOTD
        else
# The following cannot be prepended with spaces
cat <<EOFMOTD > /etc/update-motd.d/70-openvpn
#!/bin/sh
printf "%s\n" "__________________________________________________________________________________________________________"
printf "%s\n" "Inside the client GNS3:"
printf "%s\n" "-----------------------"
printf "%s\n" "Defining the remote server:"
printf "%s\n" "Edit Preferences -> Server -> Remote Servers -> Add -> ${protocol} - ${server_lan_ip_address} - ${gns3_port}"
printf "%s\n" "Edit Preferences -> Server -> Remote Servers -> Add -> enable authentication - User: ${gns3_user}"
printf "%s\n" "Edit Preferences -> Server -> Remote Servers -> Add -> enable authentication - Password: ${gns3_password}"
printf "%s\n" "Edit Preferences -> Server -> Remote Servers -> Add -> enable authentication -> OK"
printf "\n"
printf "%s\n" "Defining the remote node:"
printf "%s\n" "Edit Preferences -> Qemu VMs -> New -> Run this Qemu VM on a remote computer -> Run on <remote_server_name> -> Next -> Name -> Next"
printf "%s\n" "If the connection is successful, the Qemu binary name is retrieved"
printf "\n"
printf "%s\n" "Inside the server terminal:"
printf "%s\n" "---------------------------"
printf "%s\n" "Purge this MOTD with:"
printf "%s\n" "sudo rm -fv /etc/update-motd.d/70-openvpn"
printf "\n"
printf "%s\n" "At each boot of your server:"
printf "%s\n" "---------------------------"
printf "%s\n" "It is necessary to start GNS3 daemon with:"
printf "%s\n" ". ${python3_bin_path}/activate"
printf "%s\n" "gns3server --log /var/log/gns3/gns3.log --daemon"
printf "%s\n" "deactivate"
printf "\n"
printf "%s\n" "=========================================================================================================="
EOFMOTD
        fi
        chmod 754 /etc/update-motd.d/70-openvpn
fi

report "Saving UFW Firewall rules"
if [[ ! (-d /etc/iptables) ]]; then
        mkdir -v /etc/iptables
fi
iptables-save > /etc/iptables/rules.v4 && ip6tables-save > /etc/iptables/rules.v6

if [[ ($ufw_gns3_port_enabled == false) && ($openvpn_enabled == false) ]]; then
        report "GNS3 server port has to be manually opened on UFW firewall"
fi

if [[ ($ufw_openvpn_port_enabled == false) && ($openvpn_enabled == true) ]]; then
        report "OpenVPN port has to be manually opened on UFW firewall"
fi

report "You can now reboot the server"

echo "debconf debconf/frontend select ${original_frontend_setting}" | debconf-set-selections

exit 0