summaryrefslogtreecommitdiff
path: root/selfpublish.sh
blob: 9bb3b20c03b39321121172d3fe3fbe5286d355e6 (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
#!/bin/sh
set -e

DEFAULT_AUTH_TYPE=ed25519
DYNDNSHOST=cryptonomic.net
DEFAULT_UPSTREAM=d@cryptonomic.net:public_git/selfpublish.sh

force()
{
    [ "$FORCE" ]
}

in_group()
{
    local g
    for g in $(groups)
    do
        [ "$g" = "$1" ] && return
    done
    false
}

as_root()
{
    if [ "$(id -u)" = 0 ]
    then
        "$@"
    elif sudo -n true 2>/dev/null || in_group sudo
    then
        sudo "$@"
    else
        su -c "$*"
    fi
}

apt_install()
{
    as_root apt-get install "$@"
}

write_line_once()
{
    local line="$2" target_file="$1"
    if [ -e "$target_file" ] && grep -qF "$line" "$target_file"
    then
        return
    else
        printf %s "$line" | as_root tee -a "$target_file" >/dev/null
    fi
}

self_codename()
{
        if which lsb_release >/dev/null
        then
                lsb_release -cs
        else
                sed -ne 's/^VERSION_CODENAME=//p' /etc/os-release
        fi
}

dpkg_install()
{
    case "$(self_codename)" in
        buster)
            apt-cache policy | grep -q 'http://httpredir.debian.org/debian buster-backports/main' ||
                write_line_once /etc/apt/sources.list.d/buster-backports.list \
                    'deb      http://httpredir.debian.org/debian  buster-backports  main'
            ;;
    esac

    as_root $SHELL -c "set -$- +e; dpkg -i $*; apt-get -t buster-backports -f install"
}

dependencies()
{
    cat <<EOF
apache2 (>= 2.4.46)
basez
cgit
curl
fortune-mod
fortunes-min
gnupg (>= 2.2.14)
libssl1.1 (>= 1.1.1d)
netmask
openssl
ssh
EOF
}

fmt_dependencies()
{
    local outline=
    while read inline
    do
        if [ ! "$outline" ]
        then
            outline="Depends: $inline"
        elif [ $((${#outline} + ${#inline})) -ge 60 ]
        then
            printf '%s,\n' "$outline"
            outline=" $inline"
        else
            outline="$outline, $inline"
        fi
    done
    if [ "$outline" ]
    then
        printf '%s\n' "$outline"
    fi
}

control_file_file()
{
    printf 'File: %s %s\n' "$1" "$2"
    sed -e '  s/^[.]/../;   s/^$/./;   s/^/ /;  '
}

control_file_file_check()
{
    local prefix RESULT=0 header= data o
    tempout=$(mktemp)
    while [ "$header" ] || read header
    do
        set -- $header
        case "$1" in
            File:)

                case "$2" in
                    /*) ;;
                    *) return 1 ;;
                esac

                :> "$tempout"
                while IFS= read -r data
                do
                    case "$data" in
                        ' .'*)
                            printf '%s\n' "${data# .}" >> "$tempout"
                            continue
                            ;;
                        ' '*)
                            printf '%s\n' "${data# }" >> "$tempout"
                            continue
                            ;;
                    esac

                    if ! diff -q "$2" "$tempout"
                    then
                        RESULT=1
                        install -v -m "$3" "$tempout" -T "$2"
                    fi
                    header=$data
                    continue 2

                done
                ;;
        esac
        header=
    done
    return $RESULT
}

SELF_VERSION='0.1'
SELF_EXECUTABLE=$(realpath "$0")
control_file()
{
    cat <<EOF
Version: ${SELF_VERSION}
Package: selfpublish-dot-sh
Description: selfpublish.sh dependency package
 This package depends on the dependencies of the
 selfpublish.sh script, and is installed by that
 script to self-satisfy those dependencies.
EOF
    dependencies | fmt_dependencies
#     cat <<EOF
# File: /usr/share/doc/selfpublish-dot-sh/README.Debian 644
#  This gets overwritten :(
# EOF
    control_file_file /usr/lib/cryptonomic/cryptonomic-ipv4 755 <<'EOF'
#!/bin/bash

ipv4_check_masks_()
{
      ip=$(netmask -x "$1"/32) || return
      ip=${ip%/*}
      shift
      for cidr in "$@"
      do
            prefix=${cidr%/*}
            mask=${cidr#*/}
            if (( (ip & mask) == prefix ))
            then
                  return 1
            fi
      done
      true
}

ipv4_address_is_public()
{
      ipv4_check_masks_ "$1" $CIDR_NONPUBLIC
}

CIDR_NONPUBLIC=$(netmask -x 127.0/8 10.0/8 192.168.0/16 172.16.0/20 169.254.0/16)

ip -4 -oneline addr |
while read n dev _ inet _
do
    a=${inet%%/*}
    if ipv4_address_is_public "$a"; then
        echo "$a"
    fi
done


EOF
    control_file_file /usr/lib/cryptonomic/cryptonomic-gpg 755 <<'EOF'
#!/bin/sh

die()
{
    printf 'Error: %s\n' "$*"
    exit 1
}

process_colons()
{
    local callback="$*" IFS process_colons_break=
    set --
    while read LINE
    do
        IFS=:
        set -- $LINE
        unset IFS

        case "$1" in
            sec|pub) CURRENT_KEY=$LINE ;;
            fpr) CURRENT_FPR=${10} ;;
        esac

        if [ "$CURRENT_KEY" -a "$CURRENT_FPR" ]
        then
            $callback "$@"
        fi

        if [ "$process_colons_break" ]
        then
            break
        fi
    done
}

is_secret_key()
{
    case "$CURRENT_KEY" in
        sec:*) true ;;
        *) false ;;
    esac
}

match_domain()
{
    domain=$1
    action=$2
    shift 2
    case "$1:$2:${10%>}" in
        uid:u:*.${domain}) $action "$@";;
    esac
}

match_first_secret_key()
{
    action=$1
    shift
    is_secret_key || return
    case "$1:$2" in
        fpr:*) $action "$@"
               process_colons_break=y
               ;;
    esac
}

show_fpr()
{
    echo ${CURRENT_FPR}
}

find_secret_key_with_domain()
{
    process_colons match_domain "$1" show_fpr
}

force() { [ "$FORCE" ]; }
verbose()
{
    if [ "$VERBOSE" ]
    then
        "$@"
    fi
}
get_home()
{
    [ "$1" ] && getent passwd "$1" | (IFS=: read _ _ _ _ _ h _; echo $h)
}

GPG()
{
    set -- gpg "$@"
    if [ "$SUDO_USER" ]
    then
        su "$SUDO_USER" -c "$(bash -c 'printf "%q " "$@"' bash "$@")"
    else
        "$@"
    fi
}

ensure_key_exists()
{
    # 2. CHECK IF EXISTING SECRET KEY
    t=$(GPG -K --with-colons)
    if [ "$t" ]
    then
        # 3. CHECK IF EXISTING KEY HAS UID
        if GPG -K --with-colons | find_secret_key_with_domain "${cryptonomic_hostname#*.}" | grep -q . && ! force
        then
            return
        fi

        # 4. ADD UID TO EXISTING KEY
        gpg_default_key=$(GPG -K --with-colons | process_colons match_first_secret_key show_fpr)
        [ "$gpg_default_key" ]
        GPG --quick-add-uid "$gpg_default_key" "$uid" || force
        verbose GPG -K "$gpg_default_key"
    else
        # 2.5 GENERATE NEW KEY
        GPG --batch --passphrase '' --quick-generate-key "$uid"
        verbose GPG -K "$uid"
    fi
}

make_directories_maybe_become_root()
{
    if [ -d "$html_dir" ]
    then
        if [ -d "$hu_dir" ]
        then
            [ -w "$hu_dir" ] || exec sudo -- "$0" "$@" || die "failed to exec sudo"
        else
            [ -w "$html_dir" ] || exec sudo -- "$0" "$@" || die "failed to exec sudo"
            mkdir -m0755 -p "$hu_dir"
        fi
    else
        die "Directory not found: '$html_dir' -- you probably need to run selfpublish.sh"
        # TODO: just run selfpublish here
    fi
    find "$html_dir"/.well-known/openpgpkey/ -xdev -type d -exec chmod 755 '{}' ';'
}

process_key()
{
    local uid="$1" domain="${1#*@}" destdir="$2" tdir
    while read keyid some_uid
    do
        [ "$some_uid" = "$uid" ] || continue
        tempdir=$(mktemp -d)
        /usr/lib/gnupg/gpg-wks-client --install-key -C "$tempdir" "$keyid" "$uid" 2>/dev/null
        mkdir -p "$destdir"
        mv "$tempdir"/"$domain"/hu/* -t "$destdir"
        rm -rf "$tempdir"
    done
}

set -e

# 1. GET CRYPTONOMIC UID
cryptonomic_hostname=$(cryptonomic hostname)
[ "$cryptonomic_hostname" ]

if [ "$SUDO_USER" ]
then
    username=$SUDO_USER
    export GNUPGHOME=~$username/.gnupg
else
    username=$(id -un)
fi
[ "$username" ]

uid=${username}@${cryptonomic_hostname}
html_dir=/srv/${cryptonomic_hostname#*.}/public_html
hu_dir=$html_dir/.well-known/openpgpkey/hu

ensure_key_exists

make_directories_maybe_become_root

GPG --list-options show-only-fpr-mbox -k "$uid" 2>&- | process_key "$uid" "$hu_dir"

printf 'gpg --locate-keys %s\n' "$uid"
EOF
    control_file_file /usr/bin/cryptonomic 755 <<'EOF'
#!/bin/dash
set -e

DOMAIN=cryptonomic.net
DEFAULT_AUTH_TYPE=ed25519
HASH_TYPE=2
HOSTNAME=$(hostname --short)

die() { echo "$0: Error: $*" >&2; exit 1; }

b16_to_b32()
{
    printf %s "$1" | basez -x -d | basez -j -l | tr -d =
}

get_domain()
{
    get_sshfp "$1"

    domain=$(printf %s.%s.%s "$sshfp_b32" "$DEFAULT_AUTH_TYPE" "$DOMAIN" | tail -c64)
    domain=$(printf %s.%s "$HOSTNAME" "$domain")
}

get_sshfp()
{
    [ -f "$1" ] || return
    sshfp_b16=$(ssh-keygen -r . -f "$1" | sed -ne 's/^. IN SSHFP [0-9]* '"$HASH_TYPE"' //p') &&
        [ "$sshfp_b16" ] || die "could not determine ssh client fingerprint"
    sshfp_b32=$(b16_to_b32 "$sshfp_b16")
}

indent()
{
    sed 's/^/\t/'
}

withsetx()
{
    printf "\n\n+ %s\n" "$*"
    "$@" | indent
}

KEY_FILE=/etc/ssh/ssh_host_${DEFAULT_AUTH_TYPE}_key

delegate_command=/usr/lib/cryptonomic/cryptonomic-$1

if [ $# = 0 ]
then
    hostname=$(cryptonomic hostname)
    uid=$(id -un)@${hostname}
    2>/dev/null withsetx ssh-keyscan "$hostname"
    2>/dev/null withsetx dig +nocmd -taaaa "$hostname" +noall +answer
    2>/dev/null withsetx dig +nocmd "$hostname" +noall +answer
    2>&1 withsetx gpg --locate-keys "$uid"

elif [ "$1" = hostname ]
then
    get_domain "${KEY_FILE}".pub || exit
    printf '%s\n' "$domain"

elif [ "$1" = dyndns ]
then
    shift
    # further command line options are ssh options
    if [ -z "$(cryptonomic ipv4)" ]
    then set -- "$@" -6
    fi
    set -- ssh -i "$KEY_FILE" dyndns@"$DOMAIN" "$@" -- "$(hostname)"

    if [ -r "$KEY_FILE" ]
    then
        "$@"
    elif sudo -n true 2>/dev/null || groups | grep '\bsudo\b'
    then
        sudo -- "$@"
    else
        su -c "$(bash -c 'printf "%q " "$@"' bash "$@")"
    fi
elif [ -x "$delegate_command" ]
then
    shift
    exec "$delegate_command" "$@"

else
    echo "Usage: $0 [dyndns|hostname|gpg]" >&2
    exit 1
fi
EOF
    control_file_file /usr/bin/selfpublish.sh 755 < "$SELF_EXECUTABLE"
    echo
}

control_file_unchanged()
{
    (
        destdir=$(mktemp -d)
        trap 'rm -r "$destdir"' EXIT
        [ "$(dpkg-query -f '${Version}' -W selfpublish-dot-sh)" = "${SELF_VERSION}" ] || return

        dependencies > want-dependencies
        dpkg-query -f '${Depends}\n' -W selfpublish-dot-sh | sed 's/, */\n/g' | sort -u > have-dependencies
        diff -q want-dependencies have-dependencies
    )
}

equivocate()
{
    if dpkg-query -s selfpublish-dot-sh | grep -q '^Status: install ok installed' 2>/dev/null
    then
        if control_file_unchanged && control_file | control_file_file_check
        then
            if ! force
            then return
            fi
        fi
    fi
    which equivs-build >/dev/null 2>&1 || apt_install equivs
    (
        destdir=$(mktemp -d)
        cd "$destdir"
        control_file > ./control
        equivs-build ./control >&2
        DEB=selfpublish-dot-sh_${SELF_VERSION}_all.deb

        if ! [ "$NO_APT" ]
        then
            as_root dpkg -r selfpublish-dot-sh
            dpkg_install "$DEB"
            install -m0644 "$DEB" "$DEBDEST"
        fi
    ) || exit
}

ssh_keytag_to_path_fragment()
{
        case "$1" in
                ssh-dss) echo dsa ;;
                ecdsa-sha2-nistp256) echo ecdsa ;;
                ssh-rsa|ssh-ed25519) echo ${1#ssh-} ;;
                *) return 1 ;;
        esac
}

path_fragment_to_ssh_keytag()
{
        case "$1" in
                ssh-dss|ecdsa-sha2-nistp256|ssh-rsa|ssh-ed25519) echo $1;;
                dss|rsa|ed25519) echo ssh-$1 ;;
                dsa) echo ssh-dss ;;
                ecdsa) echo ecdsa-sha2-nistp256 ;;
                *) return 1 ;;
        esac
}

get_dyndns_domain()
{
        fragment=$(ssh_keytag_to_path_fragment "$1") || return

        host_keyfile=/etc/ssh/ssh_host_${fragment}_key
        user_keyfile=$HOME/.ssh/id_${fragment}

        set -- -q dyndns@"$DYNDNSHOST" "$HOSTNAME"

        if [ -r "$host_keyfile" ]
        then
                set -- ssh -i "$host_keyfile" "$@"

        elif in_group sudo
        then
                set -- sudo ssh -i "$host_keyfile" "$@"

        elif [ -r "$user_keyfile" ]
        then
                set -- ssh -i "$user_keyfile" "$@"

        else
                set -- ssh "$@"
        fi

        "$@"
}

enable_apache_modules()
{
        local restart=
        for MODULE in $APACHE_MODULES
        do
                if ! [ -e /etc/apache2/mods-enabled/$MODULE.load ] &&
                   ! [ "$MODULE" = cgi -a -e /etc/apache2/mods-enabled/cgid.load ]
                then
                    a2enmod $MODULE >/dev/null
                    restart=y
                fi
        done
        if [ "$restart" ]
        then
                systemctl restart apache2
        fi
}

site_conf_template()
{
cat <<END
<MDomain $DOMAIN>
        MDContactEmail webmaster@$DOMAIN
        MDCertificateAgreement accepted
        MDRequireHttps temporary
        MDMember $HOSTNAME.$DOMAIN
</MDomain>
<VirtualHost *:80>
        ServerName $DOMAIN
        ServerAlias $DOMAIN.
        Redirect / https://$DOMAIN
</VirtualHost>
<VirtualHost *:80>
        ServerAlias $HOSTNAME.$DOMAIN
        ServerAlias $HOSTNAME.$DOMAIN.
        Redirect / https://$HOSTNAME.$DOMAIN
</VirtualHost>

<VirtualHost *:443>
        ServerName $HOSTNAME.$DOMAIN
        ServerAlias $DOMAIN

        ServerAdmin webmaster@$HOSTNAME.$DOMAIN
        SSLEngine on

        ErrorLog /srv/$DOMAIN/logs/error.log
        CustomLog /srv/$DOMAIN/logs/access.log combined

        <Location "/server-status">
                SetHandler server-status
        </Location>

        DocumentRoot /srv/$DOMAIN/public_html/
        <Directory /srv/$DOMAIN/public_html>
                Options Indexes FollowSymLinks MultiViews Includes

                IndexOrderDefault Descending Date
                IndexOptions +IgnoreCase FancyIndexing
                IndexOptions +HTMLTable SuppressDescription SuppressHTMLPreamble
                IndexStyleSheet /css/autoindex.css
                IndexIgnore /unindexed /HEADER.html /css /images

                # Using an absolute url for header
                HeaderName /HEADER.html

                XBitHack on
                AllowOverride None
                Require all granted
        </Directory>

        ScriptAlias /git "/usr/lib/cgit/cgit.cgi/"
        Alias /cgit-css "/usr/share/cgit/"

</VirtualHost>
END
}

wait_for_certificate_issuance()
{
        local f state reloaded_apache=
        f=/etc/apache2/md/domains/"$1"/md.json
        local set=$-
        set +x
        echo -n Waiting for certificate... >&2
        while true
        do
            if [ -e "$f" ] && state=$(sed -ne 's/^ *"state": *\([0-9]\+\),/\1/p' "$f")
            then
                case "$state" in
                    1)
                        if ! [ "$reloaded_apache" ]
                        then
                            as_root systemctl reload apache2
                            reloaded_apache=y
                        fi
                        ;;
                    2)
                        set -$set
                        echo '  Done waiting for certificate.' >&2
                        return
                        ;;
                esac
            fi

            sleep 1
            echo -n . >&2
        done
}

install_apache_vhost()
{
        if [ -e "$SITE_CONF" ] && ! force
        then
                return
        fi

        for DIR in $APACHE_SITE_DIRS
        do
                mkdir -p "$SITE_DIR"/"$DIR"
        done

        local tmp
        tmp=$(mktemp "$SITE_CONF".XXXXXX)

        site_conf_template > "$tmp"
        mv -T "$tmp" "$SITE_CONF" || { rm -f "$tmp"; false; }
        a2ensite "$DOMAIN" >/dev/null
}

install_self_to_site()
{
        SOURCE_BASENAME=${0##*/}
        [ -d "$SITE_DIR"/public_html ] || return
        dst=$SITE_DIR/public_html/$SOURCE_BASENAME
        src=$0
        [ -e "$src" ] || return 0
        if [ ! "$src" -ef "$dst" ]
        then
                cp -Tuv "$src" "$dst" >&2
                cp -Tuv "$src" "$dst".txt >&2
        fi
        DEB="selfpublish-dot-sh_${SELF_VERSION}_all.deb"
        if [ -e "$DEB" ]
        then
            cp -Tuv "$DEB" "$SITE_DIR/public_html/$DEB"
        fi
}

get_upstream()
{
    if [ -e selfpublish.sh -a -e .git ]
    then
        UPSTREAM=$(git config --get branch.master.remote 2>/dev/null)
        case "$UPSTREAM" in
            *:*) ;;
            *) UPSTREAM=$(git remote get-url "$UPSTREAM") ;;
        esac
    fi
    UPSTREAM=${UPSTREAM:-$DEFAULT_UPSTREAM}
    [ "$UPSTREAM" ]
}

write_cgit_config()
{
    get_upstream
    cgit_scan_dir=/srv/public_git
    if ! [ -e "$cgit_scan_dir"/selfpublish.sh ]
    then
        mkdir -p "$cgit_scan_dir"
        (cd "$cgit_scan_dir"
         GIT_SSH_COMMAND='ssh -i /etc/ssh/ssh_host_ed25519_key' \
           git clone --bare "$UPSTREAM" selfpublish.sh)
    else
        git push --all "$cgit_scan_dir"/selfpublish.sh
    fi
    line="scan-path=$cgit_scan_dir"
    grep -qxF "$line" /etc/cgitrc || printf '%s\n' "$line" >> /etc/cgitrc
}

install_tls_public_certificate()
{
    local src=/etc/apache2/md/domains/"$DOMAIN"/pubcert.pem dst="$SITE_DIR"/public_html/pubcert.pem
    if [ "$src" -nt "$dst" ]
    then
        cp -Tuv /etc/apache2/md/domains/"$DOMAIN"/pubcert.pem "$SITE_DIR"/public_html/pubcert.pem
        openssl x509 -in "$dst" -noout -text > "$dst".txt
    fi
}

install_gpg_rings()
{
    cryptonomic gpg
}

configure_apache_vhost()
{
    enable_apache_modules
    install_self_to_site
    install_header_to_site
    install_tls_public_certificate
    install_gpg_rings
    write_cgit_config
}

install_header_to_site()
{
    cat > "$SITE_DIR"/public_html/HEADER.html <<EOF
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
 <head>
  <title>
    selfpublish.sh at <!--#echo var="SERVER_NAME" -->
  </title>
  <link rel="stylesheet" href="/css/autoindex.css" type="text/css">

  <style type=text/css>
    td { padding: 10px; }
    td.cmds {border: 1px solid;}

    #toggle_expand[type="checkbox"]:checked       ~ * .expand {display: "";}
    #toggle_expand[type="checkbox"]:not(:checked) ~ * .expand {display: none;}

    #main {
        text-align:left;
        margin-top: 10%;
        margin-bottom: 10%;
        font-size: 15px;
        line-height: 2em;
        border-spacing: 10px;
    }
  </style>
</head>
<body>

<input type=checkbox id=toggle_expand name=toggle_expand style='visibility: hidden' />
<table id=main>
    <tr>
        <td colspan=2 style='border: 2px solid; padding: 18px;'>
        <strong style='font-size: 20px'>selfpublish.sh</strong>
    <tr>
        <td>
        <td style='border: 1px solid; padding: 12px; text-align: center;'>
        <label for=toggle_expand>
        <strong>Install</strong>
        </label>
    <tr>
        <td>
        <td>
        <td>
        <td class=cmds> curl -OR https://<!--#echo var="SERVER_NAME" -->/selfpublish.sh && sudo bash selfpublish.sh

    <tr>
        <td>
        <td style='border: 1px solid; padding: 12px; text-align: center;'>
        <label for=toggle_expand>
        <strong>Requirements</strong>
        </label>
    <tr class=expand>
        <td>
        <td>
        <td>Distribution
        <td style='border: 1px solid; padding: 12px; text-align: center;'> <a href="https://debian.org">Debian</a> GNU/Linux
    <tr class=expand>
        <td>
        <td>
        <td>Version
        <td style='border: 1px solid; padding: 12px; text-align: center;'> <code>buster</code> or later

    <tr>
        <td>
        <td style='border: 1px solid; padding: 12px; text-align: center;'>
        <label for=toggle_expand>
        <strong>Browse source</strong>
        </label>
    <tr class=expand>
        <td>
        <td>
        <td style='text-align: right;'>Local repository:
        <td class=cmds>
                <a href="git/selfpublish.sh">
                https://<!--#echo var="SERVER_NAME" -->/git/selfpublish.sh
                </a>
    <tr class=expand>
        <td>
        <td>
        <td style='text-align: right;'>Upstream repository:
        <td class=cmds>
                <a href="https://git.cryptonomic.net/selfpublish.sh">
                https://git.cryptonomic.net/selfpublish.sh/
                </a>
    <tr class=expand>
        <td>
        <td>
        <td style='text-align: right;'>Download single file:
        <td class=cmds>
                <a href="selfpublish.sh"> https://<!--#echo var="SERVER_NAME" -->/selfpublish.sh</a>

    <tr>
        <td>
        <td style='border: 1px solid; padding: 12px; text-align: center;'>
        <label for=toggle_expand><strong>Develop (<a href="https://git-scm.com/">git</a>)</strong></label>
    <tr class=expand>
        <td>
        <td>
        <td style='text-align: right'>Clone local repository:
        <td class=cmds>
        git&nbsp;clone&nbsp;/srv/<!--#echo var="SERVER_NAME"-->/public_git/selfpublish.sh/&nbsp;&& cd&nbsp;selfpublish.sh&nbsp;&& make
    <tr class=expand>
        <td>
        <td>
        <td style='text-align: right'>Share local repository (read-only):
        <td class=cmds>
        git&nbsp;clone&nbsp;https://<!--#echo var="SERVER_NAME"-->/git/selfpublish.sh&nbsp;&& cd&nbsp;selfpublish.sh&nbsp;&& make
    <tr class=expand>
        <td>
        <td>
        <td style='text-align: right;'>To push changes upstream:
        <td class=cmds>
                git&nbsp;clone&nbsp;d@cryptonomic.net:public_git/selfpublish.sh<br>
    </tr>
    <tr class=expand>
        <td>
        <td>
        <td style='text-align: right;'>Local git repository:
        <td class=cmds>
                git&nbsp;clone&nbsp;https://<!--#echo var="SERVER_NAME"-->/git/selfpublish.sh<br>
    </tr>

</table>

<pre style=font-size:1.3em>
Fortunately,

<!--#exec cmd="/usr/games/fortune |sed 's/^/   /'" -->
</pre>
EOF
    chmod +x "$SITE_DIR"/public_html/HEADER.html
}

check_tls()
{
        local flags=$-
        set +e
        curl -s -S -I https://"$1" >/dev/null
        check_tls_result=$?
        set $flags
}

DEBDEST=$(realpath .)
[ "$NO_EQUIVS" ] || equivocate >&2

APACHE_MODULES='status md rewrite ssl include cgi'
APACHE_SITE_DIRS='logs public_html'

HOSTNAME=$(hostname --short)
DOMAIN=$(cryptonomic hostname)
cryptonomic dyndns

SITE_DIR=/srv/${DOMAIN#$HOSTNAME.}
SITE_CONF=/etc/apache2/sites-available/${DOMAIN#$HOSTNAME.}.conf

check_tls "$DOMAIN"
tls_result=$?

install_apache_vhost
configure_apache_vhost

if [ $tls_result != 0 ] || force
then
        systemctl restart apache2
        wait_for_certificate_issuance "$DOMAIN"
        systemctl reload apache2 || systemctl restart apache2
else
        systemctl reload apache2 || systemctl restart apache2
fi

check_tls "$DOMAIN"
printf '%s\n' "https://$DOMAIN/selfpublish.sh"