#!/usr/bin/env bash

set -e

baseDir=$(cd $(dirname $0) && pwd)
dataDir="$baseDir/data"

PKI_DNS=$(grep "\"dns\"" $dataDir/config.json | perl -p0e 's/.*?:\s+(.*)/\1/' | sed -e 's/\",//g' | sed -e 's/\"//g')
if [ "$PKI_DNS" == "" ]; then
    PKI_DNS="10.77.77.10:53"
fi
PKI_FQDN=$(grep fqdn $dataDir/config.json | sed -e 's/.*:[ ]*//' | sed -e 's/\",//g' | sed -e 's/\"//g')
PKI_DOMAIN=$(echo $PKI_FQDN | perl -p0e 's/.*?\.//')
PKI_DOMAIN_MODE=$(grep domain_mode $dataDir/config.json | sed -e 's/.*:[ ]*//' | sed -e 's/\",//g' | sed -e 's/\"//g')
PKI_LOCKDOWN_DOMAINS=$(grep lockdown $dataDir/config.json | grep -v domain_mode | sed -e 's/.*:[ ]*//' | sed -e 's/\",//g' | sed -e 's/\"//g')
PKI_WHITELIST_DOMAINS=$(grep whitelist $dataDir/config.json | grep -v domain_mode | sed -e 's/.*:[ ]*//' | sed -e 's/\",//g' | sed -e 's/\"//g')
PKI_ROOT_CERT_BASE="/opt/boulder/labca/certs/webpki/root-01-cert"
PKI_INT_CERT_BASE="/opt/boulder/labca/certs/webpki/issuer-01-cert"
PKI_ISSUER_NAME_ID=$(grep issuer_name_id $dataDir/config.json | sed -e 's/.*:[ ]*//' | sed -e 's/,//g' | sed -e 's/\"//g')
if [ -z "$PKI_ISSUER_NAME_ID" ] && [ -e "$PKI_INT_CERT_BASE.pem" ]; then
    nmid=$(/opt/boulder/bin/nameid -s $PKI_INT_CERT_BASE.pem)
    if [ $? == 0 ]; then
        PKI_ISSUER_NAME_ID=$nmid
        sed -i -e "s/\(^\s*\)\(\"keys\": {\)/\1\"issuer_name_id\": $PKI_ISSUER_NAME_ID,\n\1\2/g" $dataDir/config.json
    fi
fi
extended_timeout=$(grep extended_timeout $dataDir/config.json | grep true || echo "")
if [ "$extended_timeout" != "" ]; then
    PKI_EXTENDED_TIMEOUT=1
else
    PKI_EXTENDED_TIMEOUT=0
fi


perl -i -p0e "s/(\"dnsStaticResolvers\": \[\n).*?(\s+\],)/\1\t\t\t\"$PKI_DNS\"\2/igs" config/remoteva-a.json
perl -i -p0e "s/(\"dnsStaticResolvers\": \[\n).*?(\s+\],)/\1\t\t\t\"$PKI_DNS\"\2/igs" config/remoteva-b.json
perl -i -p0e "s/(\"dnsStaticResolvers\": \[\n).*?(\s+\],)/\1\t\t\t\"$PKI_DNS\"\2/igs" config/remoteva-c.json
perl -i -p0e "s/(\"dnsStaticResolvers\": \[\n).*?(\s+\],)/\1\t\t\t\"$PKI_DNS\"\2/igs" config/va.json
perl -i -p0e "s/(\"dnsStaticResolvers\": \[\n).*?(\s+\],)/\1\t\t\t\"$PKI_DNS\"\2/igs" config/bad-key-revoker.json

# Disable DOH as long as it is a feature...
sed -i -e "s/\(\"DOH\":\s*\).*/\1false/" config/remoteva-a.json
sed -i -e "s/\(\"DOH\":\s*\).*/\1false/" config/remoteva-b.json
sed -i -e "s/\(\"DOH\":\s*\).*/\1false/" config/remoteva-c.json
sed -i -e "s/\(\"DOH\":\s*\).*/\1false/" config/va.json

for fl in $(grep -Rl maxConnectionAge config/); do
    perl -i -p0e "s/(\s+\"maxConnectionAge\":[^\n]+)//igs" $fl
done
sed -i -e "s/\"issuerDomain\": \".*\"/\"issuerDomain\": \"$PKI_DOMAIN\"/" config/remoteva-a.json
sed -i -e "s/\"issuerDomain\": \".*\"/\"issuerDomain\": \"$PKI_DOMAIN\"/" config/remoteva-b.json
sed -i -e "s/\"issuerDomain\": \".*\"/\"issuerDomain\": \"$PKI_DOMAIN\"/" config/remoteva-c.json
sed -i -e "s/\"issuerDomain\": \".*\"/\"issuerDomain\": \"$PKI_DOMAIN\"/" config/va.json
sed -i -e "s/\"directoryCAAIdentity\": \".*\"/\"directoryCAAIdentity\": \"$PKI_DOMAIN\"/" config/wfe2.json

if ([ "$PKI_DOMAIN_MODE" == "lockdown" ] && [ "$PKI_LOCKDOWN_DOMAINS" != "" ]) || ([ "$PKI_DOMAIN_MODE" == "whitelist" ] && [ "$PKI_WHITELIST_DOMAINS" != "" ]); then
    perl -i -p0e "s/(\"badResultsOnly\":[^\n]*).*?(\s+)(\"checkPeriod\":)/\1\2\"skipForbiddenDomains\": true,\2\3/igs" config/cert-checker.json
    perl -i -p0e "s/(\"ignoredLints\": \[).*?(\s+)(\"w_subject_common_name_included\")/\1\2\"e_dnsname_not_valid_tld\",\2\"w_sub_cert_aia_contains_internal_names\",\2\3/igs" config/cert-checker.json
    perl -i -p0e "s/(\"ignoredLints\": \[).*?(\s+)(\"w_subject_common_name_included\")/\1\2\"e_dnsname_not_valid_tld\",\2\"w_sub_cert_aia_contains_internal_names\",\2\3/igs" config/ca.json
    perl -i -p0e "s/(\"modern\".*?)(\"ignoredLints\": \[).*?(\s+)(\"w_ext_subject_key_identifier_missing_sub_cert\")/\1\2\3\"e_dnsname_not_valid_tld\",\3\"w_sub_cert_aia_contains_internal_names\",\3\4/igs" config/ca.json
    perl -i -p0e "s/(\"shortlived\".*?)(\"ignoredLints\": \[).*?(\s+)(\"w_ext_subject_key_identifier_missing_sub_cert\")/\1\2\3\"e_dnsname_not_valid_tld\",\3\"w_sub_cert_aia_contains_internal_names\",\3\4/igs" config/ca.json

    perl -i -p0e "s/(\"pkilint:cabf.serverauth.subscriber_rsa_digitalsignature_and_keyencipherment_present\",).*?(\])/\1\n  \"pkilint:cabf.internal_domain_name\",\n  \"zlint:e_dnsname_not_valid_tld\",\n  \"zlint:w_sub_cert_aia_contains_internal_names\",\n  \"certlint:special_name_in_san\",\n  \"certlint:unknown_tld_in_san\",\n  \"certlint:br_certificates_must_include_an_http_url_of_the_ocsp_responder\",\n  \"x509lint:no_ocsp_over_http\",\n\2/igs" config/zlint.toml
    perl -i -p0e "s/(\[e_pkimetal_lint_cabf_serverauth_crl\].*)(ignore_lints = \[).*(\])/\1\2\"zlint:e_crl_next_update_invalid\"\3/igs" config/zlint.toml
fi

[ -e ../test/ident-policy.yaml ] && cp ../test/ident-policy.yaml ./ || true
[ -e ../boulder/test/ident-policy.yaml ] && cp ../boulder/test/ident-policy.yaml ./ || true
[ -e hostname-policy.yaml ] && rm hostname-policy.yaml || true
[ -e config/expired-authz-purger2.json ] && rm config/expired-authz-purger2.json || true
[ -e config/janitor.json ] && rm config/janitor.json || true
cat ident-policy.yaml | tr '\n' '\r' | sed -e "s/\r# Lockdown.*//" | tr '\r' '\n' > ident-policy.yaml.bak && mv ident-policy.yaml.bak ident-policy.yaml
cat ident-policy.yaml | tr '\n' '\r' | sed -e "s/\r# Whitelist.*//" | tr '\r' '\n' > ident-policy.yaml.bak && mv ident-policy.yaml.bak ident-policy.yaml
if [ "$PKI_DOMAIN_MODE" == "lockdown" ] && [ "$PKI_LOCKDOWN_DOMAINS" != "" ]; then
    echo >> ident-policy.yaml
    echo "# Lockdown are the domains that this LabCA instance can issue certificates for" >> ident-policy.yaml
    echo "Lockdown:" >> ident-policy.yaml
    for d in $(echo $PKI_LOCKDOWN_DOMAINS | sed -e "s/\\\r/ /g" | sed -e "s/\\\n/ /g" | tr '\r' ' '); do
        echo "  - \"$d\"" >> ident-policy.yaml
    done

    allow_public="false"
    ld_public_contacts=$(grep ld_public_contacts $dataDir/config.json | grep true || echo "")
    if [ "$ld_public_contacts" != "" ]; then
        allow_public="true"
    fi

    echo >> ident-policy.yaml
    echo "LockdownAllowPublicContacts: $allow_public" >> ident-policy.yaml
fi
if [ "$PKI_DOMAIN_MODE" == "whitelist" ] && [ "$PKI_WHITELIST_DOMAINS" != "" ]; then
    echo >> ident-policy.yaml
    echo "# Whitelist are the domains that this LabCA instance can issue certificates for" >> ident-policy.yaml
    echo "# in *addition* to all normal public domains" >> ident-policy.yaml
    echo "Whitelist:" >> ident-policy.yaml
    for d in $(echo $PKI_WHITELIST_DOMAINS | sed -e "s/\\\r/ /g" | sed -e "s/\\\n/ /g" | tr '\r' ' '); do
        echo "  - \"$d\"" >> ident-policy.yaml
    done
fi
if [ "$PKI_DOMAIN_MODE" == "lockdown" ] || [ "$PKI_DOMAIN_MODE" == "whitelist" ]; then
    sed -i -e "s/\(\"w_subject_common_name_included\"\).*\]/\1,\"e_dnsname_not_valid_tld\"\]/" config/ca.json

    REPLACEMENT=""
    REPLACEMENT2=""
    LABCA_DOMAINS=""
    if [ "$PKI_DOMAIN_MODE" == "lockdown" ] && [ "$PKI_LOCKDOWN_DOMAINS" != "" ]; then
        for d in $(echo $PKI_LOCKDOWN_DOMAINS | sed -e "s/\\\r/ /g" | sed -e "s/\\\n/ /g" | tr '\r' ' '); do
            REPLACEMENT+="    $d: 10000\r"
            REPLACEMENT2+="      - id: $d\r        comment: LabCA lockdown domain\r"
            if [ "$LABCA_DOMAINS" != "" ]; then
                LABCA_DOMAINS+=",\n"
            fi
            LABCA_DOMAINS+="\t\t\t\"$d\""
        done
    fi
    if [ "$PKI_DOMAIN_MODE" == "whitelist" ] && [ "$PKI_WHITELIST_DOMAINS" != "" ]; then
        for d in $(echo $PKI_WHITELIST_DOMAINS | sed -e "s/\\\r/ /g" | sed -e "s/\\\n/ /g" | tr '\r' ' '); do
            REPLACEMENT+="    $d: 10000\r"
            REPLACEMENT2+="      - id: $d\r        comment: LabCA whitelist domain\r"
            if [ "$LABCA_DOMAINS" != "" ]; then
                LABCA_DOMAINS+=",\n"
            fi
            LABCA_DOMAINS+="\t\t\t\"$d\""
        done
    fi
    cat rate-limit-policies.yml | tr '\n' '\r' | sed -e "s/\(must-staple.le.wtf: 10000\).*\(  registrationOverrides:\)/\1\n$REPLACEMENT\2/" | tr '\r' '\n' > rate-limit-policies.yml.bak && mv rate-limit-policies.yml.bak rate-limit-policies.yml
    cat rate-limit-policies.yml | tr '\n' '\r' | sed -e "s|\(certificatesPerFQDNSet:.*must-staple.le.wtf: 10000\).*\(certificatesPerFQDNSetFast:.*\)|\1\n${REPLACEMENT}rateLimitsURL: http://$PKI_FQDN/rate-limits\n\2|" | tr '\r' '\n' > rate-limit-policies.yml.bak && mv rate-limit-policies.yml.bak rate-limit-policies.yml

    cat config/ratelimit-overrides.yml | tr '\n' '\r' | sed -e "s/\(- CertificatesPerDomain:.*ratelimit.me.*\)\(- CertificatesPerDomain:\)/\2/" | tr '\r' '\n' > config/ratelimit-overrides.yml.bak && mv config/ratelimit-overrides.yml.bak config/ratelimit-overrides.yml
    cat config/ratelimit-overrides.yml | tr '\n' '\r' | sed -e "s/\(- CertificatesPerDomain:.*ids:\)\(.*\)\(- CertificatesPerFQDNSet:\)/\1\r$REPLACEMENT2\3/" | tr '\r' '\n' > config/ratelimit-overrides.yml.bak && mv config/ratelimit-overrides.yml.bak config/ratelimit-overrides.yml
    cat config/ratelimit-overrides.yml | tr '\n' '\r' | sed -e "s/\(- CertificatesPerFQDNSet:.*ids:\)\(.*\)/\1\r$REPLACEMENT2/" | tr '\r' '\n' > config/ratelimit-overrides.yml.bak && mv config/ratelimit-overrides.yml.bak config/ratelimit-overrides.yml

    perl -i -p0e "s/(\"labcaDomains\": \[\n).*?(\])/\1$LABCA_DOMAINS\n\t\t\2/igs" config/remoteva-a.json
    perl -i -p0e "s/(\"labcaDomains\": \[\n).*?(\])/\1$LABCA_DOMAINS\n\t\t\2/igs" config/remoteva-b.json
    perl -i -p0e "s/(\"labcaDomains\": \[\n).*?(\])/\1$LABCA_DOMAINS\n\t\t\2/igs" config/remoteva-c.json
    perl -i -p0e "s/(\"labcaDomains\": \[\n).*?(\])/\1$LABCA_DOMAINS\n\t\t\2/igs" config/va.json
fi

CRLINT=24h
CRLLIFE=96h
CRLCONF=$(grep crl_interval $dataDir/config.json | perl -p0e 's/.*?:\s+(.*)/\1/' | sed -e 's/\",//g' | sed -e 's/\"//g')
if [ "$CRLCONF" != "" ]; then
    CRLINT=$(echo $CRLCONF | cut -d "|" -f 1)
    CRLLIFE=$(echo $CRLCONF | cut -d "|" -f 2)
fi
sed -i -e "s/\"shardWidth\": \".*\"/\"shardWidth\": \"$CRLINT\"/" config/crl-updater.json
sed -i -e "s/\"updatePeriod\": \".*\"/\"updatePeriod\": \"$CRLINT\"/" config/crl-updater.json
sed -i -e "s/\"lookbackPeriod\": \".*\"/\"lookbackPeriod\": \"$CRLLIFE\"/" config/crl-updater.json
sed -i -e "s/\"lifespanCRL\": \".*\"/\"lifespanCRL\": \"$CRLLIFE\"/" config/ca.json
rm -f config/contact-exporter.json
rm -f config/nonce.json
rm -f config/ocsp-updater.json
rm -f config/wfe.json
rm -f config/orphan-finder.json
rm -f config/ca-a.json
rm -f config/ca-b.json

INT_BASE_NAME=$(basename $PKI_INT_CERT_BASE.pem)
INT_CRL_BASE_NAME=${INT_BASE_NAME/-cert/-crl}
sed -i -e "s|\"issuerURL\": \".*\"|\"issuerURL\": \"http://$PKI_FQDN/certs/$INT_BASE_NAME\"|" config/ca.json
sed -i -e "s|\"ocspURL\": \".*\"|\"ocspURL\": \"http://$PKI_FQDN/ocsp/\"|" config/ca.json
sed -i -e "s|\"crlURLBase\": \".*\"|\"crlURLBase\": \"http://$PKI_FQDN/crl/$INT_CRL_BASE_NAME\"|" config/ca.json

if [ "$PKI_EXTENDED_TIMEOUT" == "1" ]; then
    sed -i -e "s/\"timeout\": \"15s\"/\"timeout\": \"30s\"/" config/ca.json
    sed -i -e "s/\"timeout\": \"15s\"/\"timeout\": \"30s\"/" config/admin.json
    sed -i -e "s/\"timeout\": \"15s\"/\"timeout\": \"30s\"/" config/wfe2.json
    sed -i -e "s/\"timeout\": \"20s\"/\"timeout\": \"40s\"/" config/wfe2.json
    sed -i -e "s/\"timeout\": \"15s\"/\"timeout\": \"30s\"/" config/ra.json
    sed -i -e "s/\"timeout\": \"20s\"/\"timeout\": \"40s\"/" config/ra.json
    sed -i -e "s/\"timeout\": \"15s\"/\"timeout\": \"30s\"/" config/crl-storer.json
    sed -i -e "s/\"timeout\": \"15s\"/\"timeout\": \"30s\"/" config/crl-updater.json

    sed -i -e "s/timeout = .*/timeout = 30000000000 # 30 seconds/" config/zlint.toml
else
    sed -i -e "s/timeout = .*/timeout = 10000000000 # 10 seconds/" config/zlint.toml
fi
sed -i -e "s/\"timeout\": \"1s\"/\"timeout\": \"5s\"/" config/health-checker.json

for fl in $(grep -Rl maxOpenConns config/); do
    set +e
    m=$(grep "connMaxIdleTime" $fl)
    set -e
    if [ -z "$m" ]; then
        perl -i -p0e "s/([ \t]+)(\"maxOpenConns\": .*)/\1\2,\n\1\"connMaxIdleTime\": \"30s\"/g" $fl
    fi
done

rm -f test-ca.key
rm -f test-ca.key.der
rm -f test-ca.pem
rm -f test-ca.der
rm -f test-ca.p8
rm -f test-root.key
rm -f test-root.key.der
rm -f test-root.pem
rm -f test-root.der
rm -f test-root.p8

chown -R `ls -l helpers.py | cut -d" " -f 3,4 | sed 's/ /:/g'` .

if [ -e $PKI_INT_CERT_BASE.pem ] && [ -e $PKI_ROOT_CERT_BASE.pem ]; then
    [ -f setup_complete ] || touch setup_complete
fi
