#!/bin/bash
# Copyright (c) 2003-2020  Pavel Rychly, Vojtech Kovar, Milos Jakubicek

cgipath=$1
datapath=$2

if test -z "$cgipath" || test -z "$datapath"
then
    echo "Usage: setupbonito CGIPATH DATAPATH"
    exit
fi

datadir=$DESTDIR/usr/share/bonito

for d in $cgipath $datapath $datapath/cache $datapath/subcorp $datapath/options $datapath/jobs
do
    test -d $DESTDIR$d || mkdir -p $DESTDIR$d
done

if test -f $DESTDIR$cgipath/run.cgi
then
    echo "Preserving existing '$DESTDIR$cgipath/run.cgi' file."
    cd $DESTDIR$cgipath
    ln -sf run.cgi run.py
    STR=`python -c 'from run import BonitoCGI; b=BonitoCGI(); print type(b.corpname)==type("") and b.corpname'`
    if [ "$STR" != "False" ]; then
        echo "WARNING: Your run.cgi specifies corpname as Python str, now it should be Unicode instead:"
        echo "Modify \"corpname = '$STR'\" to \"corpname = u'$STR'\""
    fi
    rm -f run.py*
else
    sed -e "s,@MANATEE_REGISTRY\@,$MANATEE_REGISTRY,g" \
	-e "s,@datapath\@,$datapath,g" $datadir/run.cgi > $DESTDIR$cgipath/run.cgi
    chmod +x $DESTDIR$cgipath/run.cgi
fi

touch $DESTDIR$datapath/htpasswd

if test -f $DESTDIR$cgipath/.htaccess
then
    echo "Preserving existing '$DESTDIR$cgipath/.htaccess' file."
else
    cat >$DESTDIR$cgipath/.htaccess <<EOF
# Following might be needed for CORS compliance if XHR requests are coming from a different domain
# You may also set it in run.cgi instead, see examples there
#
#SetEnvIf Origin "http://localhost:3001|https://somewhere.else$" AccessControlAllowOrigin=\$0
#Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
#Header set Access-Control-Allow-Credentials: true
#Header set Access-Control-Allow-Headers: content-type

#<LimitExcept OPTIONS>
#AuthType Basic
#AuthName Bonito
#AuthUserFile $datapath/htpasswd
#Require valid-user
#</LimitExcept>
Alias /bonito $cgipath
<Directory $cgipath>
AllowOverride All
Options +ExecCGI
AddHandler cgi-script .cgi
</Directory>
EOF
fi

echo "Make sure $datapath/ subdirs are writable for a webserver running $cgipath/run.cgi"
echo "Edit corpus list, default corpus and other global options in $cgipath/run.cgi "
echo "Change access options in $cgipath/.htaccess and/or add usernames to $datapath/htpasswd"
