#!/usr/bin/env bash

set -e

if [ -z "${JQ}" ]; then
    echo "JQ not defined"
    exit 1
fi

OUTPUT=internal/shared/util/tlsprofiles/mozilla_data.go
INPUT=https://ssl-config.mozilla.org/guidelines/latest.json

TMPFILE="$(mktemp)"
trap 'rm -rf "$TMPFILE"' EXIT

curl -L -s ${INPUT} > ${TMPFILE}

version=$(${JQ} -r '.version' ${TMPFILE})

cat > ${OUTPUT} <<EOF
package tlsprofiles

// DO NOT EDIT, GENERATED BY ${0}
// DATA SOURCE: ${INPUT}
// DATA VERSION: ${version}

import (
"crypto/tls"
)
EOF

function generate_profile {
    cat >> ${OUTPUT} <<EOF

var ${1}TLSProfile = tlsProfile{
ciphers: cipherSlice{
cipherNums: []uint16{
EOF

    ${JQ} -r ".configurations.$1.ciphersuites.[] | . |= \"tls.\" + . + \",\"" ${TMPFILE} >> ${OUTPUT}
    ${JQ} -r ".configurations.$1.ciphers.go[] | . |= \"tls.\" + . + \",\"" ${TMPFILE} >> ${OUTPUT}

    cat >> ${OUTPUT} <<EOF
},
},
curves: curveSlice{
curveNums: []tls.CurveID{
EOF

    ${JQ} -r ".configurations.$1.tls_curves[] | . |= . + \",\"" ${TMPFILE} >> ${OUTPUT}

    version=$(${JQ} -r ".configurations.$1.tls_versions[0]" ${TMPFILE})
    version=${version/TLSv1./tls.VersionTLS1}
    version=${version/TLSv1/tls.VersionTLS10}

    cat >> ${OUTPUT} <<EOF
},
},
minTLSVersion: ${version},
}
EOF
}

generate_profile "modern"
generate_profile "intermediate"
generate_profile "old"

# Make go happy
go fmt ${OUTPUT}
