-
Notifications
You must be signed in to change notification settings - Fork 0
/
mmbuild
960 lines (719 loc) · 36.5 KB
/
mmbuild
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
#!/bin/bash
mmversion=0.3
# mmbuild create an nspawn container
# author: Badr Elmers in 2021
# https://github.com/badrelmers
# set -o xtrace ; set -xv
# export LC_ALL=en_US.UTF-8 ; export LC_CTYPE=en_US.UTF-8 ; export LANG=en_US.UTF-8
# export PYTHONIOENCODING=utf-8
# Set magic variables for current file & dir
__dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# __file="${__dir}/$(basename "${BASH_SOURCE[0]}")"
# __base="$(basename ${__file} .sh)"
# __root="$(cd "$(dirname "${__dir}")" && pwd)" # <-- change this as it depends on your app
# cd "${__dir}" || exit
###################################################
_common_functions(){
export datenow=$(date +%Y%m%d_%H%M%S)
echocolors(){
INFOC() { echo -e "\e[0;30m\e[42m" ; } # black on green
WARNC() { echo -e "\e[0;1;33;40;7m" ; } # black on yellow ;usa invert 7; y light text 1
ERRORC() { echo -e "\e[0;1;37m\e[41m" ; } # bright white on red
HIDEC() { echo -e "\e[0;1;30m\e[47m" ; } # hide color: white on grey (bright)
#HIDEC() { echo -e "\e[0;1;7;30m\e[47m" ; } # hide color: white on grey (darker)
ENDC() { echo -e "\e[0m" ; } # reset colors
INFO2C() { echo -e "\e[0;1;37m\e[44m" ; } # bright white on blue; 1 is needed sino 37 vuelve grey in mintty
INFO3C() { echo -e "\e[0;30m\e[46m" ; } # black on white blue
}
export -f echocolors
echocolors
_trap_v2(){
###################################################
# unofficial strict mode v2
###################################################
set -o errexit # -e: exit script on error
set -o nounset # -u: no unset variables
set -o pipefail # failure on any command errors
set -o errtrace # -E: shell functions inherit ERR trap
set -o functrace # -T: shell functions inherit DEBUG trap
error_handlerV2(){
# error_handlerV2()(
# print only last 3 lines of the command
local ___bash_command=$( printf '%s\n' "${BASH_COMMAND:-unkownnn}" | head -3)
HIDEC ; echo "trap..._Func: ${FUNCNAME[1]:-unkownnn}" ; ENDC
# [[ $1 -eq 0 ]] is to prevent running the trap because of trap EXIT when there is no error, i can use use trap ERR instead of trap ERR EXIT, but trap ERR do not trigger trap with undefined variables error; that s why i use trap ERR EXIT and [[ $1 -eq 0 ]]
[[ $1 -eq 0 ]] && exit 0
ERRORC
echo "_Exit: $1 _Func: ${FUNCNAME[1]:-unkownnn}"
echo "_line: ${BASH_LINENO[*]:-unkownnn} in ${BASH_SOURCE[*]:-unkownnn}"
echo "_comm: $___bash_command"
echo ''
# echo caller="$(caller)"
# echo FUNCNAMEall="${FUNCNAME[*]:-unkownnn}"
# echo FUNCNAME="${FUNCNAME}"
# echo LINENO=$2
ENDC
# read -p 'Press enter to exit the trap'
# read -p 'Press enter to exit the trap' < /dev/tty
# tty=$(readlink /proc/$$/fd/2)
# read -p 'Press enter to exit the trap' < $tty
# exit 0 will prevent trigerring trap again in outside funcion after runing in an inner function
# exit 0 do not seem to do anything, ERR ya hace ke el script exit , so i do no think i need to use exit here
# exit 1 will trigger trap EXIT if trap ERR was trigered first, so the trap is run twice
# exit 0
# )
}
# trap - EXIT is needed to prevent runing the trap twice when ERR is trigered
# why use ERR and EXIT? because undefined variables will not trigguer the trap
# trap 'error_handlerV2 $? ${LINENO}; trap - EXIT' EXIT ERR
# i will use this instead because i will use trap exit bellow to clean whene there is errors
trap 'error_handlerV2 $? ${LINENO}' ERR
export -f error_handlerV2
}
_trap_v2
}
_common_functions
export -f _common_functions
################################################################
export datenowForHostname=$(date +%Y%m%d%H%M%S)
_create_container(){
########################################################
# variables
########################################################
# I need to create the repository manually to be conscient of the location and prevent bad things
# repository=./
# repository=/media/ssd2/_MyNspawnStore
# sin haveged aprece un error :random: 7 urandom warning(s) missed due to ratelimiting
common_packages="haveged,dbus,apt-transport-https,wget,curl,locales,tzdata,man-db,manpages,dialog,procps,sudo,net-tools,nano,ifupdown,iproute2,apt-utils,less,lnav,ca-certificates,bash-completion"
# ca-certificates solve this error: ERROR: The certificate of ‘github.com’ doesn't have a known issuer.
# https://stackoverflow.com/questions/9224298/how-do-i-fix-certificate-errors-when-running-wget-on-an-https-url-in-cygwin
# bash-completion
# tab in qemu in debian do not work, i cannot complet apt in... with tab
# https://unix.stackexchange.com/questions/312456/debian-apt-not-apt-get-autocompletion-not-working
# ifupdown
# ubuntu 18 instala netplan pero si instalo ifupdown se usara ifupdown al configurar /etc/network/interfaces
########################################################
___validate_hostname(){
# test if new name conform the hostname requirements:
# test if var have only a-z 0-9 - and 63 char max and not begin or end with - and not have repeated -
# https://www.freedesktop.org/software/systemd/man/org.freedesktop.hostname1.html
# Here are some recommendations to follow when generating a static (internet) hostname from a pretty name:
# Generate a single DNS label only, not an FQDN. That means no dots allowed. Strip them, or replace them by "-".
# It's probably safer not to use any non-ASCII chars, even if DNS allows this in some way these days. In fact, restrict your charset to a-zA-Z0-9, -.
# Try to avoid creating repeated "-", as well as "-" as the first or last char.
# Limit the hostname to 63 chars, which is the length of a DNS label
# Uppercase charaacters should be replaced with their lowercase equivalents.
# man 5 hostname
# The /etc/hostname file configures the name of the local system that is set during boot using the sethostname(2) system call. It should contain a single newline-terminated hostname string. Comments (lines starting with a `#') are ignored. The hostname may be a free-form string up to 64 characters in length; however, it is recommended that it consists only of 7-bit ASCII lower-case characters and no spaces or dots, and limits itself to the format allowed for DNS domain name labels, even though this is not a strict requirement.
# https://www.freedesktop.org/software/systemd/man/hostname.html
# /etc/hostname
# The file should contain a single newline-terminated hostname string. Comments (lines starting with a "#") are ignored. The hostname should be composed of up to 64 7-bit ASCII lower-case alphanumeric characters or hyphens forming a valid DNS domain name. It is recommended that this name contains only a single label, i.e. without any dots. Invalid characters will be filtered out in an attempt to make the name valid, but obviously it is recommended to use a valid name and not rely on this filtering.
[[ "$1" =~ ^- ]] && { WARNC ; echo 'name should not begin with -' ; ENDC ; exit 223; }
[[ "$1" =~ -$ ]] && { WARNC ; echo 'name should not end with -' ; ENDC ; exit 223; }
# --+ match succesive -
[[ "$1" =~ --+ ]] && { WARNC ; echo 'name should not contain succesive repeated -' ; ENDC ; exit 223; }
[[ ${#1} -gt 63 ]] && { WARNC ; echo 'name should not contain more than 63 char' ; ENDC ; exit 223; }
[[ "$1" =~ ^[a-z0-9-]+$ ]] || { WARNC ; echo 'name should contain only a-z (no uppercase) 0-9 or - chars' ; ENDC ; exit 223; }
# _____________
# i will never arrive to this because all this is done above, pero por si las moscas
# this will test if var have only a-z 0-9 - and 63 char max and not begin or end with -
# first [a-z0-9] is to test that hostname do not begin with -
# last [a-z0-9] is to test that hostname do not end with -
# [a-z0-9-]{1,61} match 1 to 61 of a-z 0-9 or -
[[ "$1" =~ ^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$ ]] || { WARNC ; echo 'name is invalid' ; ENDC ; exit 223; }
# tests : all this have to gave errors
# ___validate_hostname '-dash'
# ___validate_hostname 'dash-'
# ___validate_hostname 'dash--dash'
# ___validate_hostname 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaz' # 63char+z
# ___validate_hostname 'test.com'
# ___validate_hostname 'test_'
}
CTname=$1
OSFLAVOUR=$2
OSversion=$3
ROOTPASSWD=$4
shift 4
___validate_hostname "${CTname}"
# validate too the CT clone name that I will use bellow
CTname_clone=${CTname}-clean
___validate_hostname "${CTname_clone}"
repochoice(){
selectrepo(){
test -f /etc/_mm.conf || { WARNC ; echo 'no /etc/_mm.conf found. you have to define a repository where I will save the containers. create one and add it to /etc/_mm.conf ...exiting' ; ENDC ; exit 223 ; }
echo "The following repositories were found in the config file /etc/_mm.conf; select one:"
# this is to prevent problems with folders with space in path
local IFSold="$IFS"
local IFS=$'\n'
mmrepos=$(cat /etc/_mm.conf)
# set the prompt used by select, replacing "#?"
PS3="Use a number to select a folder or select 'exit' to cancel: "
# allow the user to choose a file
select myyrepo in $mmrepos exit ; do
local IFS="$IFSold"
# leave the loop if the user says 'exit'
if [[ "$myyrepo" == exit ]]; then exit 223; fi
# complain if no file was selected, and loop to ask again
if [[ "$myyrepo" == "" ]]
then
echo "'$REPLY' is not a valid number"
continue
fi
# ===begin handling files aki=================
# now we can use the selected file
echo "you selected: $myyrepo"
myrepository="$myyrepo"
# ===end handling files=======================
# it'll ask for another unless we leave the loop
break
done
}
# __________________
tput bold
tput setaf 2
PS3='Please enter your choice: '
options=(
"install to a defined repository in /etc/_mm.conf"
"install to actual dir: $PWD"
)
select opt in "${options[@]}" ;do
tput sgr0
case $opt in
*"install to actual"*) repository="$PWD" ; break ;;
*"install to a defined repository"*)
selectrepo
repository="${myrepository}"
if [ -z "${repository:-}" ]; then
WARNC ; echo 'no repository defined. create one and add it to /etc/_mm.conf ...exiting' ; ENDC
exit 223
fi
if [ ! -d "${repository:-}" ]; then
WARNC ; echo 'this repository does not exit. create it first with mkdir ...exiting' ; ENDC
exit 223
fi
break ;;
*) echo "invalid option $REPLY"
# break
exit 223 ;;
esac
done
}
repochoice
########################################################
# main
########################################################
_clean() {
# si nspawn_finished no es igual finished borramos la imagen
if [ "${nspawn_finished:-}" = "NOTfinished" ] ; then
HIDEC ; echo "begin cleaning..." ; ENDC
echo "nspawn creation not finished so let s remove the folder: ${CTname_DIR:-unkownennn}"
test -d ${CTname_DIR:-unkownennn} && rm -rf ${CTname_DIR:-unkownennn}
test -d ${CTname_DIR:-unkownennn}-clean && rm -rf ${CTname_DIR:-unkownennn}-clean
test -f /var/lib/machines/${CTname:-unkownennn} && rm /var/lib/machines/${CTname:-unkownennn}
test -f /var/lib/machines/${CTname:-unkownennn}-clean && rm /var/lib/machines/${CTname:-unkownennn}-clean
# disable trap and fail on errors sino me saldra el bash on errors
# set +euo pipefail
# set +E
# trap - ERR EXIT RETURN INT
# esta linea es importante sino se ejecuta el trap ERR si la linea de arriba da exit 1
echo "end cleaning..."
exit 223
fi
}
# this will run always, EXIT es para cuando este script se ejecuta como script file, y RETURN es para cuando ejecuto la function directamente desde un shell
# trap _clean EXIT RETURN INT
trap _clean EXIT INT
nspawn_finished=NOTfinished
# TODO: this is not needed i already did it above , i can delete it
test -d "${repository}" || { ERRORC ; echo "repository of nspawn containers was not created. create it manually first. you told me to use : ${repository}" ; ENDC ; exit 223; }
cd "${repository}"
########################################################
# sometimes I will want to install the container in another disk so:
# I will create a config file where I will save the repositories I use so i can control them all with mm
grep -Fq "${repository}" /etc/_mm.conf || { echo "${repository}" >> /etc/_mm.conf ; }
########################################################
CTname_DIR=${repository}/_MyMM/${CTname}
test -d ${CTname_DIR} && { WARNC ; echo "container dir exist: ${CTname_DIR}" ; ENDC ; trap '' EXIT RETURN INT ; exit 223 ; }
mkdir -p _MyMM/${CTname}
cd _MyMM/${CTname}
# TODO: if i install systemd from backport then i have to use systemd-container of backport too, so here I have to detect if systemd was installed from backport or not
command -v systemd-nspawn > /dev/null || apt-get install -y systemd-container
command -v debootstrap > /dev/null || apt-get install -y debootstrap
INFOC ; echo "Installing $OSversion into ${CTname}..." ; ENDC
########################################################
if [ $OSFLAVOUR == "debian" ]; then
#repo=http://snapshot.debian.org/archive/debian/20201215T204137Z
#reposecure=http://snapshot.debian.org/archive/debian/20201215T204137Z
repo=http://deb.debian.org/debian
# reposecure=http://security.debian.org
reposecure=http://deb.debian.org/debian-security
components=main,contrib,non-free
if [ $OSversion == testing ] ; then
apt_source="
deb ${repo} testing main contrib non-free
# deb-src ${repo} testing main contrib non-free
deb ${repo} testing-updates main contrib non-free
# deb-src ${repo} testing-updates main contrib non-free
deb ${reposecure} testing-security main contrib non-free
# deb-src ${reposecure} testing-security main contrib non-free
"
elif [ $OSversion == unstable ] ;then
apt_source="
#unstable have no backport or security
deb ${repo} unstable main contrib non-free
# deb-src ${repo} unstable main contrib non-free
"
else
# Suite name for security updates changing with Debian 11 "bullseye"
# https://lists.debian.org/debian-devel-announce/2019/07/msg00004.html
# https://unix.stackexchange.com/questions/529009/debian-testing-upgrade-buster-to-bullseye-version-no-server-for-security
# over the last years we had people getting confused over <suite>-updates
# (recommended updates) and <suite>/updates (security updates). Starting
# with Debian 11 "bullseye" we have therefore renamed the suite including
# the security updates to <suite>-security.
# An entry in sources.list should look like
# deb http://security.debian.org/debian-security bullseye-security main
# For previous releases the name will not change.
# antes era buster/updates ahora es bullseye-security
secu_suffix='-security'
[ $OSversion == buster ] && secu_suffix='/updates'
apt_source="
deb ${repo} ${OSversion} main contrib non-free
# deb-src ${repo} ${OSversion} main contrib non-free
deb ${repo} ${OSversion}-updates main contrib non-free
# deb-src ${repo} ${OSversion}-updates main contrib non-free
deb ${repo} ${OSversion}-backports main contrib non-free
# deb-src ${repo} ${OSversion}-backports main contrib non-free
deb ${reposecure} ${OSversion}${secu_suffix} main contrib non-free
# deb-src ${reposecure} ${OSversion}${secu_suffix} main contrib non-free
"
fi
elif [ $OSFLAVOUR == "ubuntu" ]; then
repo=http://archive.ubuntu.com/ubuntu
# reposecure=http://security.ubuntu.com/ubuntu
reposecure=http://archive.ubuntu.com/ubuntu
components=main,restricted,universe,multiverse
apt_source="
## universe multiverse is ENTIRELY UNSUPPORTED by the Ubuntu
deb ${repo} ${OSversion} main restricted universe multiverse
deb ${repo} ${OSversion}-updates main restricted universe multiverse
deb ${repo} ${OSversion}-backports main restricted universe multiverse
deb ${reposecure} ${OSversion}-security main restricted universe multiverse
# deb-src ${repo} ${OSversion} main restricted universe multiverse
# deb-src ${repo} ${OSversion}-updates main restricted universe multiverse
# deb-src ${repo} ${OSversion}-backports main restricted universe multiverse
# deb-src ${reposecure} ${OSversion}-security main restricted universe multiverse
"
fi
########################################################
INFOC ; echo "debootstrap $OSFLAVOUR $OSversion..." ; ENDC
mkdir -p ${repository}/debootstrap_pkg/${OSFLAVOUR}_${OSversion}
debootstrap --merged-usr --cache-dir ${repository}/debootstrap_pkg/${OSFLAVOUR}_${OSversion} --components=${components} --include=$common_packages $* $OSversion ${CTname_DIR} $repo
########################################################
# config login/pass
########################################################
INFOC ; echo "config login/pass" ; ENDC
# Set root password
chroot ${CTname_DIR} bash -c "echo 'root:${ROOTPASSWD}' | chpasswd"
# bug: machinectl login gave error:incorrect password
echo "pts/0" >> ${CTname_DIR}/etc/securetty
# al usar machinectl en vez de nspawn se usa pts/1, asi ke hacemos eso tb
echo "pts/1" >> ${CTname_DIR}/etc/securetty
########################################################
# autologin
########################################################
# Nspawn console
# To configure auto-login for a systemd-nspawn container, override console-getty.service:
mkdir ${CTname_DIR}/etc/systemd/system/console-getty.service.d
cat <<'EOF' > ${CTname_DIR}/etc/systemd/system/console-getty.service.d/nspawnautologin.conf
[Service]
ExecStart=
ExecStart=-/sbin/agetty --noclear --autologin root --keep-baud console 115200,38400,9600 $TERM
EOF
# If machinectl login my-container method is used to access the container, also add --autologin username to [email protected] template that manages pts/[0-9] pseudo ttys:
mkdir ${CTname_DIR}/etc/systemd/system/[email protected]
cat <<'EOF' > ${CTname_DIR}/etc/systemd/system/[email protected]/machinectlautologin.conf
[Service]
ExecStart=
ExecStart=-/sbin/agetty --noclear --autologin root --keep-baud pts/%I 115200,38400,9600 $TERM
EOF
############################
# locale
############################
INFOC ; echo "configure locale" ; ENDC
chroot ${CTname_DIR} /bin/bash <<"EOF"
apt-get update
apt-get install -y locales
test -f /etc/locale_ORG.gen || cp /etc/locale.gen /etc/locale_ORG.gen
echo 'en_US.UTF-8 UTF-8' > /etc/locale.gen
locale-gen --purge 'en_US.UTF-8'
update-locale 'LANG=en_US.UTF-8'
dpkg-reconfigure --frontend noninteractive locales
EOF
############################
# network
############################
INFOC ; echo "configure network" ; ENDC
TODOOOOOOO(){
test -f ${CTname_DIR}/etc/network/interfaces && cp ${CTname_DIR}/etc/network/interfaces ${CTname_DIR}/etc/network/interfacesORG
cat <<EOF > ${CTname_DIR}/etc/network/interfaces
auto lo
iface lo inet loopback
auto ${ETH_DEVICE}
iface ${ETH_DEVICE} inet dhcp
# ubuntu18 de debootstrap al configurar /etc/network/interfaces with dhcp it will run dhclient and leave it open listening on port 68 on 0.0.0.0
# pero no encontre nadie haciendolo pero funciona biennn
up pkill dhclient || true
EOF
}
############################
# hosts & hotname
############################
INFOC ; echo "configure hosts & hostname" ; ENDC
echo ${CTname} > ${CTname_DIR}/etc/hostname
cat <<EOF > ${CTname_DIR}/etc/hosts
127.0.0.1 localhost
127.0.1.1 ${CTname}
# The following lines are desirable for IPv6 capable hosts
::1 localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
EOF
############################
# dns
############################
INFOC ; echo "configure dns" ; ENDC
test -f ${CTname_DIR}/etc/resolv.conf && cp -a ${CTname_DIR}/etc/resolv.conf ${CTname_DIR}/etc/resolv.confORG
chroot ${CTname_DIR} systemctl disable systemd-resolved
chroot ${CTname_DIR} rm /etc/resolv.conf
echo '
nameserver 8.8.8.8
nameserver 8.8.4.4
nameserver 1.1.1.1
' > ${CTname_DIR}/etc/resolv.conf
############################
# apt source list
############################
INFOC ; echo "configure apt source list" ; ENDC
test -f ${CTname_DIR}/etc/apt/sources.list && cp ${CTname_DIR}/etc/apt/sources.list ${CTname_DIR}/etc/apt/sources.listORG
echo "${apt_source}" > ${CTname_DIR}/etc/apt/sources.list
############################
# configure bash
############################
INFOC ; echo "configure bash" ; ENDC
# history
cat <<'EOF' > ${CTname_DIR}/etc/profile.d/badr_bash_profile.sh
if [ -n "${BASH_VERSION-}" -a -n "${PS1-}" ]; then
#anadido por badr
alias grep='grep --color'
alias ls='ls --color=auto'
export HISTCONTROL=ignoreboth
# https://stackoverflow.com/questions/9457233/unlimited-bash-history
# Eternal bash history.
# ---------------------
# Undocumented feature which sets the size to "unlimited".
# http://stackoverflow.com/questions/9457233/unlimited-bash-history
# esto tiene un bug , si el fichero llega a 2gb bash volvera muy lentooo
# export HISTFILESIZE=
# export HISTSIZE=
# or
export HISTTIMEFORMAT="[%F %T] "
export HISTFILESIZE=9999
export HISTSIZE=1000
# Change the file location because certain bash sessions truncate .bash_history file upon close.
# http://superuser.com/questions/575479/bash-history-truncated-to-500-lines-on-each-login
export HISTFILE=~/.bash_eternal_history
# Force prompt to write history after every command.
# http://superuser.com/questions/20900/bash-history-loss
#PROMPT_COMMAND="history -a; $PROMPT_COMMAND"
fi
EOF
########################################################
# PS1
# https://unix.stackexchange.com/questions/329581/why-is-debians-default-bash-shell-colourless
# http://www.linuxfromscratch.org/blfs/view/svn/postlfs/profile.html
# al crear un nuevo user a new .bashrc will be created wich contain PS1 and it will override this PS1 bellow (i can see what bash read with bash -lx or bash -x)
cat <<'EOF' >> ${CTname_DIR}/etc/skel/.bashrc
#badr_PS1
if [ ! -z "$PS1" ]; then
NORMAL="\[\e[0m\]"
RED="\[\e[1;31m\]"
GREEN="\[\e[1;32m\]"
if [[ $EUID == 0 ]] ; then
PS1="$RED\u@\h [ $NORMAL\w$RED ]# $NORMAL"
else
PS1="$GREEN\u@\h [ $NORMAL\w$GREEN ]\$ $NORMAL"
fi
unset RED GREEN NORMAL
fi
EOF
# users already created will not have the content of /etc/skel/.bashrc so the following will force root user for example to have my PS1
cat <<'EOF' > ${CTname_DIR}/etc/profile.d/badr_PS1.sh
#badr_PS1
if [ ! -z "$PS1" ]; then
NORMAL="\[\e[0m\]"
RED="\[\e[1;31m\]"
GREEN="\[\e[1;32m\]"
if [[ $EUID == 0 ]] ; then
PS1="$RED\u@\h [ $NORMAL\w$RED ]# $NORMAL"
else
PS1="$GREEN\u@\h [ $NORMAL\w$GREEN ]\$ $NORMAL"
fi
unset RED GREEN NORMAL
fi
EOF
# en ubuntu instalado por debootstrap viene con /root/.bashrc configurado con su PS1, asi ke vamos a anadir el PS1 a ello tb
cat <<'EOF' >> ${CTname_DIR}/root/.bashrc
#badr_PS1
if [ ! -z "$PS1" ]; then
NORMAL="\[\e[0m\]"
RED="\[\e[1;31m\]"
GREEN="\[\e[1;32m\]"
if [[ $EUID == 0 ]] ; then
PS1="$RED\u@\h [ $NORMAL\w$RED ]# $NORMAL"
else
PS1="$GREEN\u@\h [ $NORMAL\w$GREEN ]\$ $NORMAL"
fi
unset RED GREEN NORMAL
fi
EOF
########################################################
# fzf ctrl-r alternative
fzf_met1(){
git clone --depth 1 https://github.com/junegunn/fzf.git ${CTname_DIR}/usr/local/lib/fzf
# chroot ${CTname_DIR} /usr/local/lib/fzf/install --all
chroot ${CTname_DIR} /usr/local/lib/fzf/install --bin --no-key-bindings --no-completion --no-update-rc --no-bash --no-zsh --no-fish
cat <<'EOF' > ${CTname_DIR}/etc/profile.d/badr_fzf.sh
# to uninstall do
# /usr/local/lib/fzf/uninstall
# Setup fzf
# ---------
if [[ ! "$PATH" == */usr/local/lib/fzf/bin* ]]; then
export PATH="${PATH:+${PATH}:}/usr/local/lib/fzf/bin"
fi
# Auto-completion
# ---------------
[[ $- == *i* ]] && source "/usr/local/lib/fzf/shell/completion.bash" 2> /dev/null
# Key bindings
# ------------
source "/usr/local/lib/fzf/shell/key-bindings.bash"
EOF
}
fzf_met1
fzf_met2(){
# this uses apt install but ubuntu 16 y 18 no tiene fzf
if [ "$OSversion" != "xenial" -a "$OSversion" != "bionic" ] ; then
cat <<'EOF' > ${CTname_DIR}/etc/profile.d/badr_fzf.sh
# ctrl-r alternative but without run it so i can edit it before run it :) alhamdolillah
if [ -n "${BASH_VERSION-}" -a -n "${PS1-}" ]; then
bind '"\C-r": "\C-x1\e^\er"'
bind -x '"\C-x1": __fzf_history';
__fzf_history (){
__ehc $(history | fzf --tac --tiebreak=index | perl -ne 'm/^\s*([0-9]+)/ and print "!$1"')
}
__ehc(){
if [[ -n $1 ]] ; then
bind '"\er": redraw-current-line'
bind '"\e^": magic-space'
READLINE_LINE=${READLINE_LINE:+${READLINE_LINE:0:READLINE_POINT}}${1}${READLINE_LINE:+${READLINE_LINE:READLINE_POINT}}
READLINE_POINT=$(( READLINE_POINT + ${#1} ))
else
bind '"\er":'
bind '"\e^":'
fi
}
# show file content preview
alias ff="fzf --preview 'cat {}'"
fi
EOF
fi
}
########################################################
# only lnav 0.9 have themes; i need a white theme
chroot ${CTname_DIR} /bin/bash <<"EOF"
wget https://github.com/tstack/lnav/releases/download/v0.9.0/lnav_0.9.0_amd64.deb
dpkg -i lnav_0.9.0_amd64.deb
echo h | lnav -n -c ':config /ui/default-colors true'
EOF
# esto blokea el script ,funciona in interactive console solo
# timeout 1 lnav -c ':config /ui/default-colors true'
########################################################
# creat alias wrapper for machinectl/nspawn to simplify interactive use
# no lo usare ya ke uso ahora mm
# echo '
# if [ -n "${BASH_VERSION-}" -a -n "${PS1-}" ] ; then
# badr nspawn alias
# alias m=machinectl
# alias mi="machinectl list-images"
# fi
# ' > /etc/profile.d/badr_nspawn.sh
########################################################
# config
########################################################
INFOC ; echo "configure machinectl" ; ENDC
# register my container with machinectl
ln -s ${CTname_DIR} /var/lib/machines/${CTname}
########################################################
# create service override file
########################################################
mkdir ${CTname_DIR}/_MyMMfiles
# save service override file inside container dir so i can use it when i use mm clone for example
# the defaut here is to run the container with full privilges and host network
cat <<'EOF' > ${CTname_DIR}/_MyMMfiles/nspawn_override_service.conf
[Service]
###===============================================
### Raise maximum number of open file descriptors
###===============================================
###LimitNOFILE=infinity
MaxNoFile="--rlimit=RLIMIT_NOFILE=99999:200000"
###===============================================
###net config
###===============================================
###_________________
###host networking
###_________________
###to use Host network which have internet natively just comment all the Environment=network bellow because nspawn will use Host network when we do not use any network flag
###_________________
###private networking
###_________________
###this is the default when using machinectl but internet do not work without a dhcp server or iptables, i will never use this because i do not know yet how to make it to have internet yet
#Environment="networkVAR=--network-veth"
###_________________
###NAT networking using a private bridge
###_________________
###this creat a private network where i can set a static private ip (NAT) but need iptables to make containers talk to outside
#Environment="networkVAR=--network-bridge=mynspawnbr0"
###_________________
###bridge networking
###_________________
###this creatse a bridge which i can use with my second ip in hetzner
#Environment="networkVAR=--network-bridge=vmbr0"
### NB: ahora usa $networkVAR y no uses ${networkVAR}; porke si no uso networkVAR (como en el caso de ###host networking), entonces $networkVAR dara un vacio mientras ${networkVAR} dara "" , y "" hara problemas si ${networkVAR} esta en el medio del comando a ejecutar pk se considerara como parte del commando y el servicio fallara al iniciarlo. pero por si acaso quiero usar ${networkVAR} entonces deja la al final en ExecStart line sino me dara error al dejar la variable vacia.
###la difrencia entre $networkVAR y ${networkVAR} es ke la primera si tiene espacio sera parseada y considerada como dos argumentos, mientra la segunda si tiene espacio no se hara parsing y se considerar como un argumento.
###===============================================
###unprivileged or privileged
###===============================================
#to change between privileged and unprivileged just uncomment the one I want (uncomment only what have one # not the ones with 3 ###)
# esto es importante , hay ke eliminar el commando ke se usa por defecto sino ExecStart se ejecutara dos veces:
ExecStart=
########### NB: lee esto
###cuidado: do not forget this: do this when I run a container as unprivileged (with -U) then I run it as privileged (without -U) then I want to run it again as unprivileged (with -U) , so i need to do this before runing the container with -U again
###update: tb al ejecutar el container without -U after using -U I have to use this or i will get a message about sudo do not have suid blablabla for example.
###asi ke cada vez ke cambio entre comandos ke usan -U y comandos ke no usan -U hay ke usar esto
#ExecStart=/usr/bin/systemd-nspawn --quiet --keep-unit --boot --link-journal=try-guest --settings=override --machine=%i --private-users=0 --private-users-chown $networkVAR $MaxNoFile
###_________________
###unprivileged
###_________________
###this is the default when i use machinectl to start the containers
#ExecStart=/usr/bin/systemd-nspawn --quiet --keep-unit --boot --link-journal=try-guest --settings=override --machine=%i -U $networkVAR $MaxNoFile
###_________________
###normal privileged
###_________________
#improve nspawn from 3M to 15M ops/s (this is relative to your computer)
Environment=SYSTEMD_SECCOMP=0
ExecStart=/usr/bin/systemd-nspawn --quiet --keep-unit --boot --link-journal=try-guest --settings=override --machine=%i --private-users=false --capability=all $networkVAR $MaxNoFile
#no olvides disable spectre/metldown mitigations, it improves ops from 15M to 24M ops/s
#los siguentes no anaden mas performance sino mas opciones solo, usalos solo si algun programa no funciona dentro de nspawn
###_________________
###super super privileged
###_________________
#this is too much i think, I need this only if I want docker or perf report inside nspawn
# disable seccomp, this will improve performance a lot, it need systemd v247
#Environment=SYSTEMD_SECCOMP=0
# this variable will allow to run docker inside nspawn, but need --bind=/sys/fs/cgroup too. remember that --bind=/sys/fs/cgroup cannot be used without SYSTEMD_NSPAWN_USE_CGNS=0
#Environment=SYSTEMD_NSPAWN_USE_CGNS=0
#this is needed for example for perf report to use dbg symbols of /proc/kallsyms see nspawn disables /proc/kallsyms
#Environment=SYSTEMD_NSPAWN_API_VFS_WRITABLE=yes
#ExecStart=/usr/bin/systemd-nspawn --quiet --keep-unit --boot --link-journal=try-guest --settings=override --machine=%i --private-users=false --capability=all --bind=/sys/fs/cgroup $networkVAR $MaxNoFile
###_________________
###super super super privileged
###_________________
#allow to create all devices in cat /proc/devices
#see allow device creation in nspawn
#Environment=SYSTEMD_SECCOMP=0
#Environment=SYSTEMD_NSPAWN_USE_CGNS=0
#Environment=SYSTEMD_NSPAWN_API_VFS_WRITABLE=yes
#ExecStart=/usr/bin/systemd-nspawn --quiet --keep-unit --boot --link-journal=try-guest --settings=override --machine=%i --private-users=false --capability=all --bind=/sys/fs/cgroup --property=DeviceAllow="block-* rwm" --property=DeviceAllow="char-* rwm" $networkVAR $MaxNoFile
#I can even gave it more privileges, see in onenote:
#*Super* Privileged Container Concept
###===============================================
###end of priv and unpriv container
###===============================================
#sometimes i need to reload systemctl to detect my changes to this file so use:
# systemctl daemon-reload
EOF
# copy service override file to /etc/systemd/system
mkdir /etc/systemd/system/systemd-nspawn@${CTname}.service.d
cp ${CTname_DIR}/_MyMMfiles/nspawn_override_service.conf /etc/systemd/system/systemd-nspawn@${CTname}.service.d/nspawn_override_service.conf
systemctl daemon-reload
########################################################
# save a copy of this script and nspawn version and CT name
########################################################
# crea una copia de este script junto con la imagen por si acaso la necesito para saber como he creado la imagen
declare -f _create_container > ${CTname_DIR}/_MyMMfiles/_script_used_to_create_container.sh
echo "echo 'usage as script file:
chmod +x _script_used_to_create_container.sh
source _script_used_to_create_container.sh ; _create_container'" >> ${CTname_DIR}/_MyMMfiles/_script_used_to_create_container.sh
# save nspawn version used:
echo ___systemd-nspawn version____________________ > ${CTname_DIR}/_MyMMfiles/_nspawn_versions.txt
systemd-nspawn --version >> ${CTname_DIR}/_MyMMfiles/_nspawn_versions.txt
echo ___systemd-nspawn dependencies______________________ >> ${CTname_DIR}/_MyMMfiles/_nspawn_versions.txt
apt show systemd-container >> ${CTname_DIR}/_MyMMfiles/_nspawn_versions.txt
# save CT name
echo 'this file contain all the container names used before cloning and renaming the container' >> ${CTname_DIR}/_MyMMfiles/_container_names.txt
echo "name:${CTname} ___ date:$(date)" >> ${CTname_DIR}/_MyMMfiles/_container_names.txt
########################################################################################
# take snapshot. let this the last one
########################################################################################
# best practice
# best practice is to create a copy of this container before doing more changes , so i can clone this clean container whenever i want to do testing...etc
mm clone ${CTname} ${CTname_clone}
# i do not need to register the clean version i can use mm to do it , it s better because it will create the service override ...Etc
# ln -s ${CTname_DIR}-clean /var/lib/machines/${CTname}-clean
# puesto que mm clone will register the cloned CT (because the CT was registred above) then we will unregistre it
mm unregister ${CTname_clone}
########################################################
INFO2C ; echo "SUCCESS!" ; ENDC
INFO3C
echo "
===run with:============================================================
mm run ${CTname}
mm ls
mm lsa
"
ENDC
nspawn_finished=finished
}
_build(){
if [ $# -lt 4 ] ; then
_help
# WARNC ; echo "usage: $0 <image-file> <OS name> <OSversion> [optional debootstrap args]" 1>&2 ; ENDC
WARNC ; echo "error: need 4 args at least" 1>&2 ; ENDC
exit 223
else
_create_container $@
fi
}
# create a quick guide with the command I need to execute in the shell
_help(){
echo "
======================================================================================
usage:
mmbuild imagename (as Hostname az09-) OS OS release pass [optional debootstrap args]
mmbuild buster${datenowForHostname} debian buster bbbbbbnn
mmbuild bullseye${datenowForHostname} debian bullseye bbbbbbnn
mmbuild testing${datenowForHostname} debian testing bbbbbbnn
mmbuild unstable${datenowForHostname} debian unstable bbbbbbnn
mmbuild xenial${datenowForHostname} ubuntu xenial bbbbbbnn
mmbuild bionic${datenowForHostname} ubuntu bionic bbbbbbnn
mmbuild focal${datenowForHostname} ubuntu focal bbbbbbnn
"
}
# cmd=${1:-}
# shift || true # esta es importante para poder usar $@ sin ke contenga $1 ke se consume in case...
# case "$cmd" in
case $@ in
help|h) _help ;;
"") _help ;;
*) _build $@ ;;
esac