package Libelle::Middleware::IsolateBranch;
use strict;
use warnings;

use parent 'Plack::Middleware';
use Plack::Request;
use Plack::Response;

my %BRANCHES = (
    aaa => {
        css => 'aaa.css',
        search => 'branch:ICF',
    },
    ccc => {
        css => 'bbb.css',
        search => 'branch:BBB',
    },
    xxx => {
        css => 'ccc.css',
        search => 'branch:CCC',
    },
); # could be passed when init middleware

my $regex = '^/('.join('|',keys %BRANCHES).')/';

sub call {
    my $self = shift;
    my $env  = shift;

    my $path = $env->{PATH_INFO};
    if ($path =~m{$regex}) {
        my $branch = $1;
        $path=~s{^/$branch/}{/};

        $env->{PATH_INFO} = $path;
        $env->{OPAC_CSS_OVERRIDE} = $BRANCHES{$branch}->{css};
        $env->{OPAC_SEARCH_LIMIT} =  $BRANCHES{$branch}->{search};
        $env->{OPAC_LIMIT_OVERRIDE} = '1';

        # call Koha
        my $res = Plack::Response->new(@{$self->app->($env)});

        # fix links in response, ugly and maybe not stable
        if ($res->content_type =~m{^text/html}) {
            my $raw_body = $res->body;
            my $body = ref($raw_body) eq 'ARRAY' ? join('',@$raw_body) : $raw_body;
            $body=~s{/cgi-bin}{/$branch/cgi-bin}g;
            $res->body($body);
        }
        elsif ($res->status == 302) {
            my $target = $res->location;
            $target=~s{/cgi-bin}{/$branch/cgi-bin}g;
            $res->redirect($target);
        }

        return $res->finalize;
    }
    else {
        return $self->app->($env);
    }
}

1;

=pod

Needs to be enabled in /etc/koha/plack.psgi

  use Libelle::Middleware::IsolateBranch;
  ...
  builder {
    ...
    enable 'Libelle::Middleware::IsolateBranch'; # between Static and SetEnv
    ...
  }

And needs some Apache Config adaptions:

  /etc/koha/apache-shared-opac-plack.conf
  RewriteRule "^/(aaa|bbb|ccc)$" "/$1/" [L,PT]
  ProxyPassMatch "^/(aaa|bbb|ccc)/" "http://koha:5005/$1/opac/opac-main.pl"
  ProxyPassMatch "^/(aaa|bbb|ccc)/cgi-bin/koha" "http://koha:5005/$1/opac"

  ProxyPassReverse /aaa/ "http://koha:5005/aaa/opac/opac-main.pl"
  ProxyPassReverse /aaa/cgi-bin/koha "http://koha:5005/aaa/opac"
  ProxyPassReverse /bbb/ "http://koha:5005/bbb/opac/opac-main.pl"
  ProxyPassReverse /bbb/cgi-bin/koha "http://koha:5005/bbb/opac"
  ProxyPassReverse /ccc/ "http://koha:5005/ccc/opac/opac-main.pl"
  ProxyPassReverse /ccc/cgi-bin/koha "http://koha:5005/ccc/opac"



