#!/bin/sh

set -eu

IFS=','

sitesubd="$1"; shift;
sitezone="${sitesubd#*.}"
sitepref="${sitesubd%%.*}"

cfg_script="$0"
cfg_srcdir=$(cd -- "${cfg_script%/*}/" ; pwd -P)

# header
cat << _EOF
server {
    listen                [::]:80;
    server_name           ${sitesubd};
    return                301 https://\$server_name\$request_uri;
}

server {
    listen                [::]:443;
    server_name           ${sitesubd};

_EOF

# indexed locations
for sitedir in $@; do

cat << _EOF
    location /${sitedir} {
        root              /srv/www/htdocs/\$host;
        autoindex         on;
        ssi               on;
    }

_EOF

done

# root directory
cat << _EOF
    location / {
        root              /srv/www/htdocs/\$host;
        index             index.html index.htm;
        ssi               on;
    }

_EOF

# ssl and footer
cat << _EOF
    ssl_certificate           /srv/webroot/${sitezone}/ssl/fullchain.pem;
    ssl_certificate_key       /srv/webroot/${sitezone}/ssl/privkey.pem;
    ssl_trusted_certificate   /srv/webroot/${sitezone}/ssl/chain.pem;

    include conf.d/ssl_params;
}
_EOF
