#!/bin/bash

# Retrieve arguments
domain=$(sudo yunohost app setting searx domain)
path=$(sudo yunohost app setting searx path)
is_public=$(sudo yunohost app setting searx is_public)

# Remove trailing "/" for next commands
path=${path%/}

# Check depends installation
sudo apt-get install git build-essential libxslt-dev python-dev python-virtualenv python-pybabel zlib1g-dev -y


# Check Swap
if [ $(sudo swapon -s | wc -l) = 1 ];
then
	mount | grep /tmp | grep tmpfs > /dev/null 2>&1
	if [ $? = 1 ];
	then
		tmp_swap_file=/tmp/searx_swapfile
	else
		tmp_swap_file=/var/cache/
	fi
	sudo dd if=/dev/zero of=$tmp_swap_file bs=1M count=256
	sudo chmod 600 $tmp_swap_file
	sudo mkswap $tmp_swap_file
	sudo swapon $tmp_swap_file
fi

final_path=/opt/yunohost/searx
sudo cp -r ../sources/* $final_path
sudo bash -c "source $final_path/bin/activate && pip install -r $final_path/requirements.txt --upgrade"

# Disable swapfile
if [[ -v "$tmp_swap_file" ]];
then
    sudo swapoff $tmp_swap_file
    sudo rm -f $tmp_swap_file
fi

# Remove trailing "/" for next commands if installing on a subpath
if [ "$path" != "/" ];
then
        path=${path%/}
fi

#Configuration Searx
sudo cp ../conf/settings.yml $final_path/searx/
sudo sed -i -e "s/ultrasecretkey/`openssl rand -hex 16`/g" $final_path/searx/settings.yml
if [ "$path" != "/" ];
then
    sudo sed -i -e "s@ynhbaseurl@https://$domain$path/@g" $final_path/searx/settings.yml
else
    sudo sed -i -e "s@ynhbaseurl@False@g" $final_path/searx/settings.yml
fi

# Set permissions to searx directory
sudo useradd searx -d $final_path
sudo chown searx:searx -R $final_path

# Copy uwsgi config
sudo cp ../conf/searx.ini /etc/uwsgi/apps-available/

# Modify Nginx configuration file and copy it to Nginx conf directory
sudo sed -i "s@PATHTOCHANGE@$path@g" ../conf/nginx.conf*
if [ "$path" != "/" ];
then
    sudo cp ../conf/nginx.conf-noroot /etc/nginx/conf.d/$domain.d/searx.conf
else
    sudo cp ../conf/nginx.conf /etc/nginx/conf.d/$domain.d/searx.conf
fi

# Fix permission
#sudo find $final_path/ -type d -exec chmod 2755 {} \;
#sudo find $final_path/ -type f -exec chmod g+r,o+r {} \;

## Reload Nginx and regenerate SSOwat conf
sudo service nginx reload
sudo service uwsgi restart

if [ "$is_public" = "Yes" ];
then
    sudo yunohost app setting searx skipped_uris -d
    sudo yunohost app setting searx unprotected_uris -v "/"
fi
sudo yunohost app ssowatconf

