#!/bin/bash

exname=$(basename $0)

compose_core=$(which compose-core) || {
    echo "Requires compose-core executable to be in \$PATH." >&2
    exit 1
}

fetch-def() {
    local path="$1" fname="$2"
    ( . "$path" 1>&2 || {
          echo "Failed to load '$path'." >&2
          exit 1
      }
      declare -f "$fname"
    )
}


prefix_cmd="
. /etc/shlib

include common
include parse

. ../lib/common

$(fetch-def "$compose_core" yaml_get_values)
$(fetch-def "$compose_core" yaml_get_interpret)

" || {
    echo "Couldn't build prefix cmd" >&2
    exit 1
}




# mock
relation-get() {
    local key="$1"
    echo "$CFG" | shyaml get-value "$key" 2>/dev/null
}
export -f relation-get

cfg-get-value() {
    local key="$1"
    shyaml get-value "$key" 2>/dev/null
}
export -f cfg-get-value

get_service_relations() {
    printf "%s\0" "${RELATIONS[@]}"
}
export -f get_service_relations

export state_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
trap "rm -rf \"$state_tmpdir\"" EXIT

##
## Tests
##

try "
apache_vhost_statement publish_dir ,http, '\
' www.example.com"
noerror
is out '<VirtualHost *:80>

    ServerAdmin contact@www.example.com
    ServerName www.example.com

    ServerSignature Off
    CustomLog /var/log/apache2/www.example.com_access.log combined
    ErrorLog /var/log/apache2/www.example.com_error.log
    ErrorLog syslog:local2


    ##
    ## Publish directory /var/www/www.example.com
    ##

    DocumentRoot /var/www/www.example.com

    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>

    <Directory /var/www/www.example.com>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride all
        Allow from all
    </Directory>

    ## Forbid any cache, this is only usefull on dev server.
    #Header set Cache-Control "no-cache"
    #Header set Access-Control-Allow-Origin "*"
    #Header set Access-Control-Allow-Methods "POST, GET, OPTIONS"
    #Header set Access-Control-Allow-Headers "origin, content-type, accept"

</VirtualHost>' RTRIM

##
## Aliases
##

try "
apache_vhost_statement publish_dir ,http, '
server-aliases:
- toto
' www.example.com"
noerror
is out reg 'ServerAlias toto'


try "
apache_vhost_statement publish_dir ,http, '
server-aliases:
- toto
- titi
' www.example.com"
noerror
is out reg 'ServerAlias toto'
is out reg 'ServerAlias titi'


##
## Creds
##

try "
apache_vhost_statement publish_dir ,http, ''  www.example.com
" "credentials allow all"
noerror
is out reg 'Allow from all'


try "
apache_vhost_statement publish_dir ,http, '
creds:
  toto: xxx
  titi: yyy
' www.example.com
" "credentials with basic auth user/pass"
noerror
is out reg 'AuthType basic'
is out reg 'Require valid-user'


##
## proxy
##

try "
apache_vhost_statement web_proxy ,http, '
target: popo:3333
creds:
  toto: titi
' www.example.com
" "proxy explicit target"
noerror
is out reg 'ProxyPass / http://popo:3333/'
is out part '
        <Location / >
            AuthType basic
            AuthName "private"
            AuthUserFile /etc/apache2/sites-enabled/www.example.com.passwd
            Require valid-user
            ProxyPassReverse http://popo:3333/
        </Location>
'


try "
apache_vhost_statement web_proxy ,http, '
target: popo:3333
apache-proxy-pass-options: nocanon
' www.example.com
" "proxy proxy-pass options"
noerror
is out reg 'ProxyPass / http://popo:3333/ nocanon'

##
## ssl
##

try "
apache_vhost_statement web_proxy ,https, '
ssl: true
target: popo:3333
' www.example.com
" "ssl default generation (ssl-cert-snakeoil)"
noerror
is out reg 'VirtualHost \*:443'
is out reg '<IfModule mod_ssl.c>'
is out reg 'SSLEngine On'
is out reg 'SSLProxyEngine On'
is out reg 'ssl-cert-snakeoil'
is out reg 'CustomLog /var/log/apache2/s-www.example.com_access.log combined'


try "
RELATIONS=()
apache_vhost_statement web_proxy ,https, '
ssl:
  ca-cert: a
  key: b
  cert: c
target: popo:3333
' www.example.com
" "ssl providing keys inline"
noerror
is out reg 'SSLCertificateFile /etc/ssl/certs/www.example.com.pem'
is out reg 'SSLCertificateKeyFile /etc/ssl/private/www.example.com.key'
is out reg 'SSLCACertificateFile /etc/ssl/certs/www.example.com-ca.pem'


##
## CustomRules
##

try "
apache_vhost_statement web_proxy ,https, '
ssl:
  ca-cert: a
  key: b
  cert: c
apache-custom-rules: |
  RewriteEngine On
  RewriteCond %{QUERY_STRING} !skin=formanoo
  RewriteRule ^(/web/webclient/home.*)$ $1?skin=formanoo [L,QSA,R=302]
target: popo:3333
' www.example.com
" "custom rules"
noerror
is out reg 'RewriteEngine On'


##
## double def
##

try "
apache_vhost_statement web_proxy ,https,http, '
ssl:
  ca-cert: a
  key: b
  cert: c
apache-custom-rules: |
  RewriteEngine On
  RewriteCond %{QUERY_STRING} !skin=formanoo
  RewriteRule ^(/web/webclient/home.*)$ $1?skin=formanoo [L,QSA,R=302]
target: popo:3333
' www.example.com
" "both http and https"
noerror
is out '<VirtualHost *:80>

    ServerAdmin contact@www.example.com
    ServerName www.example.com

    ServerSignature Off
    CustomLog /var/log/apache2/www.example.com_access.log combined
    ErrorLog /var/log/apache2/www.example.com_error.log
    ErrorLog syslog:local2


    ##
    ## Custom rules
    ##

    RewriteEngine On
    RewriteCond %{QUERY_STRING} !skin=formanoo
    RewriteRule ^(/web/webclient/home.*)$ ?skin=formanoo [L,QSA,R=302]


    ##
    ## Proxy declaration towards popo:3333
    ##

    <IfModule mod_proxy.c>
        ProxyRequests Off
        <Proxy *>
            Order deny,allow
            Allow from all
        </Proxy>
        ProxyVia On
        ProxyPass / http://popo:3333/ retry=0
        <Location / >
            Allow from all
            ProxyPassReverse http://popo:3333/
        </Location>

    </IfModule>

    RequestHeader set "X-Forwarded-Proto" "http"

    ## Fix IE problem (httpapache proxy dav error 408/409)
    SetEnv proxy-nokeepalive 1

    ## Forbid any cache, this is only usefull on dev server.
    #Header set Cache-Control "no-cache"
    #Header set Access-Control-Allow-Origin "*"
    #Header set Access-Control-Allow-Methods "POST, GET, OPTIONS"
    #Header set Access-Control-Allow-Headers "origin, content-type, accept"

</VirtualHost>

<IfModule mod_ssl.c>
  <VirtualHost *:443>

      ServerAdmin contact@www.example.com
      ServerName www.example.com

      ServerSignature Off
      CustomLog /var/log/apache2/s-www.example.com_access.log combined
      ErrorLog /var/log/apache2/s-www.example.com_error.log
      ErrorLog syslog:local2


      ##
      ## Custom rules
      ##

      RewriteEngine On
      RewriteCond %{QUERY_STRING} !skin=formanoo
      RewriteRule ^(/web/webclient/home.*)$ ?skin=formanoo [L,QSA,R=302]


      ##
      ## Proxy declaration towards popo:3333
      ##

      <IfModule mod_proxy.c>
          ProxyRequests Off
          <Proxy *>
              Order deny,allow
              Allow from all
          </Proxy>
          ProxyVia On
          ProxyPass / http://popo:3333/ retry=0
          <Location / >
              Allow from all
              ProxyPassReverse http://popo:3333/
          </Location>
          SSLProxyEngine On
      </IfModule>

      RequestHeader set "X-Forwarded-Proto" "https"

      ## Fix IE problem (httpapache proxy dav error 408/409)
      SetEnv proxy-nokeepalive 1

      ## Forbid any cache, this is only usefull on dev server.
      #Header set Cache-Control "no-cache"
      #Header set Access-Control-Allow-Origin "*"
      #Header set Access-Control-Allow-Methods "POST, GET, OPTIONS"
      #Header set Access-Control-Allow-Headers "origin, content-type, accept"

      ##
      ## SSL Configuration
      ##

      SSLEngine On

      SSLCertificateFile /etc/ssl/certs/www.example.com.pem
      SSLCertificateKeyFile /etc/ssl/private/www.example.com.key
      SSLCACertificateFile /etc/ssl/certs/www.example.com-ca.pem

      SSLVerifyClient None

  </VirtualHost>
</IfModule>' RTRIM




##
## single def no domain
##

try "
apache_vhost_statement publish_dir ,http, '
apache-custom-rules: |
  RewriteEngine On
  RewriteCond %{QUERY_STRING} !skin=formanoo
  RewriteRule ^(/web/webclient/home.*)$ $1?skin=formanoo [L,QSA,R=302]
target: popo:3333
' ""
" "http without domain"
noerror
is out '<VirtualHost *:80>

    ServerAdmin webmaster@localhost

    ServerSignature Off
    CustomLog /var/log/apache2/access.log combined
    ErrorLog /var/log/apache2/error.log
    ErrorLog syslog:local2


    ##
    ## Custom rules
    ##

    RewriteEngine On
    RewriteCond %{QUERY_STRING} !skin=formanoo
    RewriteRule ^(/web/webclient/home.*)$ ?skin=formanoo [L,QSA,R=302]


    ##
    ## Publish directory /var/www/html
    ##

    DocumentRoot /var/www/html

    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>

    <Directory /var/www/html>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride all
        Allow from all
    </Directory>

    ## Forbid any cache, this is only usefull on dev server.
    #Header set Cache-Control "no-cache"
    #Header set Access-Control-Allow-Origin "*"
    #Header set Access-Control-Allow-Methods "POST, GET, OPTIONS"
    #Header set Access-Control-Allow-Headers "origin, content-type, accept"

</VirtualHost>' RTRIM


try "
apache_vhost_statement ssh_tunnel ,https, '
ssl: true
apache-custom-rules: |
  RewriteEngine On
  RewriteCond %{QUERY_STRING} !skin=formanoo
  RewriteRule ^(/web/webclient/home.*)$ $1?skin=formanoo [L,QSA,R=302]
target: popo:3333
' 'ssh.example.com'
" "ssh tunnel"
noerror
is out '
<IfModule mod_ssl.c>
  <VirtualHost *:443>

      ServerAdmin contact@ssh.example.com
      ServerName ssh.example.com

      ServerSignature Off
      CustomLog /var/log/apache2/s-ssh.example.com_access.log combined
      ErrorLog /var/log/apache2/s-ssh.example.com_error.log
      ErrorLog syslog:local2


      ##
      ## Custom rules
      ##

      RewriteEngine On
      RewriteCond %{QUERY_STRING} !skin=formanoo
      RewriteRule ^(/web/webclient/home.*)$ ?skin=formanoo [L,QSA,R=302]


      ##
      ## SSH Tunnel
      ##

      #HostnameLookups On
      ProxyRequests On
      AllowConnect 22
      #ProxyVia on

      ### Deny everything by default

      <Proxy *>
          Order deny,allow
          Deny from all
      </proxy>

      ### Accept redirect only to same domain

      <Proxy ssh.example.com>
          Order deny,allow
          Allow from all
      </Proxy>

      ## Forbid any cache, this is only usefull on dev server.
      #Header set Cache-Control "no-cache"
      #Header set Access-Control-Allow-Origin "*"
      #Header set Access-Control-Allow-Methods "POST, GET, OPTIONS"
      #Header set Access-Control-Allow-Headers "origin, content-type, accept"

      ##
      ## SSL Configuration
      ##

      SSLEngine On

      SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem
      SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key


      SSLVerifyClient None

  </VirtualHost>
</IfModule>' RTRIM