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

cgipath=$1
datapath=$2

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

datadir=$DESTDIR${3-/usr/share/bonito}

for d in $cgipath $datapath $datapath/cache $datapath/subcorp $datapath/options $datapath/jobs $datapath/registration
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."
    #pushd $DESTDIR$cgipath
    #2to3 -w $DESTDIR$cgipath/run.cgi
    #popd
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
touch $DESTDIR$datapath/registration/users
touch $DESTDIR$datapath/registration/invalid_users
touch $DESTDIR$datapath/registration/admins

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
HttpProtocolOptions Unsafe
<Directory $cgipath>
AllowOverride All
Options +ExecCGI -Indexes
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"
