#!/bin/bash

set -x

mkdir -p /srv/hg
chown user:user /srv/hg

cat <<EOF >/srv/hg/hgweb.cgi
#!/usr/bin/env python3
# See also https://mercurial-scm.org/wiki/PublishingRepositories

# Path to repo or hgweb config to serve (see 'hg help hgweb')
config = b"/srv/hg/hgweb.config"

# Uncomment to send python tracebacks to the browser if an error occurs:
# import cgitb; cgitb.enable()

from mercurial import demandimport
demandimport.enable()

from mercurial.hgweb import hgweb, wsgicgi

application = hgweb(config)
wsgicgi.launch(application)
EOF
chmod a+xr /srv/hg/hgweb.cgi

cat <<EOF >/srv/hg/hgweb.config
[paths]
/ = /srv/hg/*

[web]
style = gitweb
encoding = "UTF-8"

baseurl = /

deny_push = *
allow_archive = bz2, gz, zip
EOF
chmod a+r /srv/hg/hgweb.config

cat <<EOF >/etc/apache2/sites-available/hg.conf
<VirtualHost hg.defun.work:*>
    DocumentRoot /srv/hg
    ServerName hg.defun.work

    Alias "/.well-known/acme-challenge/" "/srv/www/letsencrypt/.well-known/acme-challenge/"
    <Directory "/srv/www/letsencrypt/">
        Require all granted
    </Directory>

    # Discourage bots indexing HG: Python is slow and cause OOM kills...
    <IfModule mod_headers.c>
      Header add "X-Robots-Tag" "noindex, nofollow"
    </IfModule>

    ScriptAliasMatch  ^/(.*)  /srv/hg/hgweb.cgi/\$1

    <Directory "/srv/hg/">
        Options +ExecCGI
        Require all granted
        AllowOverride None
        AddHandler cgi-script .cgi
        <IfModule mod_cgi.c>
          CGIScriptTimeout 1s
        </IfModule>
        <IfModule mod_cgid.c>
          CGIDScriptTimeout 1s
        </IfModule>
    </Directory>
</VirtualHost>

<IfModule mod_ssl.c>
  <VirtualHost hg.defun.work:443>
    DocumentRoot /srv/hg
    ServerName hg.defun.work

    <IfModule mod_headers.c>
      Header add "X-Robots-Tag" "noindex, nofollow"
    </IfModule>

    ScriptAliasMatch  ^/(.*)  /srv/hg/hgweb.cgi/\$1

    <Directory "/srv/hg/">
        Options +ExecCGI
        Require all granted
        AllowOverride None
        AddHandler cgi-script .cgi
        <IfModule mod_cgi.c>
          CGIScriptTimeout 1s
        </IfModule>
        <IfModule mod_cgid.c>
          CGIDScriptTimeout 1s
        </IfModule>
    </Directory>
  </VirtualHost>
</IfModule>
EOF

a2ensite hg
a2enmod cgid
a2enmod headers
service apache2 reload
