#!/bin/bash

# Retrieve arguments
domain=$(sudo yunohost app setting wordpressms domain)
path=$(sudo yunohost app setting wordpressms path)
admin_wordpress=$(sudo yunohost app setting wordpressms admin)
language=$(sudo yunohost app setting wordpressms language)
is_public=$(sudo yunohost app setting wordpressms is_public)
multisite=$(sudo yunohost app setting wordpressms multisite)

root_pwd=$(sudo cat /etc/yunohost/mysql)

final_path=/var/www/wordpressms

db_name=wordpressms

if [[ "$admin_wordpress" = "" ]];
then
    mysql -u root -p$root_pwd $db_name -e "select MAX(user_login) from wp_users where user_status=0 INTO OUTFILE '/tmp/wordpressuser';"
    admin_wordpress=$(cat /tmp/wordpressuser)
    sudo rm -f /tmp/wordpressuser
fi

if [[ "$language" = "" ]];
then
    language=$(sudo grep WPLANG $final_path/wp-config.php | cut -d"'" -f4)
fi

if [[ "$is_public" = "" ]];
then
    mysql -u root -p$root_pwd $db_name -e "select option_value from wp_options WHERE option_name='active_plugins' INTO OUTFILE '/tmp/wordpressispublic';"
    grep -q http-authentication /tmp/wordpressispublic
    if [[ $? -eq 0 ]];
    then
        is_public=Yes
    else
        is_public=No
    fi
    sudo rm -f /tmp/wordpressispublic
fi

# Check if admin is not null
if [[ "$admin_wordpress" = "" || "$is_public" = "" || "$language" = "" ]]; then
    echo "Unable to upgrade, please contact support"
    exit 1
fi


# Modify Nginx configuration file and copy it to Nginx conf directory
sed -i "s@PATHTOCHANGE@$path@g" ../conf/nginx.conf
sed -i "s@ALIASTOCHANGE@$final_path/@g" ../conf/nginx.conf


if [ $is_public = "Yes" ];
then
    grep -q "define('FORCE_SSL_ADMIN', true);" $final_path/wp-config.php
    if [[ ! $? -eq 0 ]];
    then
        echo "define('FORCE_SSL_ADMIN', true);" | sudo tee -a $final_path/wp-config.php
    else 
        sudo sed -i "s@//define('FORCE_SSL_ADMIN@define('FORCE_SSL_ADMIN@g" $final_path/wp-config.php
    fi
else
	sudo sed -i "s@#--PRIVATE--@@g" ../conf/nginx.conf
fi

if [ "$multisite" = "Yes" ];
then
    sudo sed -i "s@#--MULTISITE--@@g" ../conf/nginx.conf
fi

sudo cp ../conf/nginx.conf /etc/nginx/conf.d/$domain.d/wordpressms.conf

# Reload Nginx
sudo service nginx reload