#!/bin/bash -e
clear
echo "===================================="
echo " Browsum Wordpress WP-CLI Installer "
echo "===================================="
echo

# Declare variables for Websupport REST API
#websupport_api_key=5d76596e-d361-4d
#websupport_api_secret=342c4f3b6b228beda3e8

# Determining domain to be installed from ls
domain=`ls $HOME | grep -v browsumwp | grep -v wp-cli.phar`
echo "Detected domain: $domain"

#Setting default variable values
type="main"
path=""
#Asking for domain related setup data
echo "Will this be a main domain or a subdomain install? [main/sub]"
read -e type
if [ "$type" == "sub" ]
then
echo "So this will be a subdomain install!"
echo
echo "Subdomain: "
read -e sub
path="/home/$domain/sub/$sub/"
mkdir -p $path
domain="${sub}.${domain}"
echo
echo "Domain: $domain"
echo "Path: $path"
 else
echo "So this will be a main domain install!"
echo
path="/home/$domain/web/"
echo "Domain: $domain"
echo "Path: $path"
fi

# Check if WS Users API is reachable
# API docs: https://rest.websupport.sk/docs/v1.user#users
# Note: This uses the "Get a user detail" API call to see if the WS Users API is reachable or not, looks for the HTTP status code 200
# Note: The script exits if the WS Users API is not reachable
#status_code=$(curl --write-out %{http_code} --silent --output /dev/null -u ${websupport_api_key}:${websupport_api_secret} "https://rest.websupport.sk/v1/user/self")

#echo
#if [[ "$status_code" -eq 200 ]] ; then
#  echo "WS Users API reachable, all good!"
#else
#  echo "WS Users API unreachable, exiting..." && exit 0
#fi

## The below is WorkInProgress, commented out
## Set the user_id from the API based on user_email which we already know
## API docs: https://developer.okta.com/docs/api/resources/users#get-user-with-login
#user_id=$(curl -s -X GET -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: SSWS ${api_token}" "https://${org}.okta.com/api/v1/users/${user_email}" | jq -r '.id')
#echo
#echo "WS user id:" $user_id
#
## Creating the DB using Websupport API
#curl "https://rest.websupport.sk/v1/user/:id/hosting/:id/db" -v -u key:secret -H "Content-Type: application/json" -X POST \ 
#-d '{"domain": "aaa.sk", "dbName": "testdb", "dbType": "mariadb55", "dbUser": "testdb", "defaultCollation": "utf8_general_ci", "note": "test"}'

echo
# Asking for DB/user related setup data
echo "Wordpress MySQL db/user: "
read -e dbnameanduser
echo "Wordpress MySQL password: "
read -e dbpass
echo "Client's first name: "
read -e clientfirstname
echo

# Changing to $HOME folder
cd $HOME && echo "Change to HOME directory [OK]" || echo "Change to HOME directory [FAIL]"

## Downloading WP-CLI and making it executable - since Websupport added WP-CLI support into Shell, no need to curl download WP-CLI in this script
#curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar && echo "Downloaded WP-CLI [OK]" || echo "Couldn't download WP-CLI [FAIL]"
#mkdir $HOME/bin && echo "Creation of $HOME/bin [OK]" || echo "Creation of $HOME/bin [FAIL]"
#mv wp-cli.phar $HOME/bin/wp && chmod +x $HOME/bin/wp && echo "Moving wp-cli.phar to $HOME/bin/wp and making it executable [OK]" || echo "Moving wp-cli.phar to $HOME/bin/wp and making it executable [FAIL]"
#echo

#Change dir to path (sub or web directory)
cd $path && echo "Change to $path directory [OK]" || echo "Change to $path directory [FAIL]"

# Download WordPress
# 2017-12-15 the Hungarian locale was not available for download, so to download Hungarian next time add --locale=hu_HU before the --path
# 2018-01-26 The --locale=hu_HU was put back to place
# 2020-05-12 the hu_HU locale was again not available for download, but this time we needed the HU interface, so removing the --locale=hu_HU wasn't an option, instead we try to add --version, and use an older version which might include the hu_HU locale
# wp versions: https://wordpress.org/download/releases/
#wp core download --locale=hu_HU --path=$path --version=latest
wp core download --locale=hu_HU --path=$path --version=5.4

echo

wp config create --dbname=$dbnameanduser --dbuser=$dbnameanduser --dbpass=$dbpass --dbhost=mariadb103.websupport.sk:3313 --dbprefix=wbmstr_ --extra-php <<PHP
define( 'DISALLOW_FILE_EDIT', true );
PHP

# Install WordPress
echo
wp core install --url="http://browsum.com" --title=$domain --admin_user=webmester.sk --admin_password=W3bm3573r.5k$clientfirstname --admin_email=browsum@browsum.com

# GENERAL OPTIONS
# Update WordPress Home/Siteurl URLs due to install bug with --url=""
wp option update siteurl 'http://'$domain
wp option update home 'http://'$domain
echo
wp option update blogname $domain
wp option update blogdescription $domain
wp option update users_can_register 0
echo
wp option update timezone_string 'Europe/Bratislava'
#wp option update date_format 'Y. F j.'
wp option update time_format 'H:i'
wp option update start_of_week 1 #Start of week Monday
echo

# Remove all temp files
wp transient delete --all && echo "Deleted all transients [OK]" || echo "Could not delete transients [FAIL]"
echo

# Remove all default posts and pages
echo "Removing all default posts and pages"
wp post list --post_type=page,post --field=ID | xargs wp post delete
echo

## Install BackWPup separately from other plugins
#echo "Install BackWPup separately from other plugins"
#wp plugin install backwpup --activate --quiet
#echo

## TODO Workaround - BackWPup installation kills the NEXT command following it, so I've duplicated the smilies setting as a workaround
#wp option update use_smilies 0

# Writing
wp option update use_smilies 0

# Discussion
wp option update default_pingback_flag 1 #Attempt to notify any blogs linked to from the article
wp option update default_ping_status 'closed' #Do not Allow pingbacks and trackbacks on new articles
wp option update default_comment_status closed #Do not Allow people to post comments on new articles

wp option update require_name_email 1 #Comment author must fill out name and e-mail
wp option update comment_registration 1 #Users must be registered and logged in to comment
wp option update comments_notify 1 #Email me if Anyone posts a comment
wp option update comments_notify 1 #Email me if A comment is held for moderation
wp option update comment_moderation 1 #Comment must be manually approved
wp option update show_avatars 1
wp option update avatar_default 'mystery'
echo

# Permalinks
wp option update permalink_structure '/%postname%/'
wp option update uploads_use_yearmonth_folders 1
echo

# Delete bloat prepacked bloat themes, twentyfifteen to be added
for theme in twentysixteen twentyseventeen
 do
  wp theme delete $theme
  echo
 done

# Delete bloat prepacked bloat plugins
for plugin in akismet hello azigen magyar-video-embed
 do
  wp plugin delete $plugin
  echo
 done

# Install/activate needed plugins, not including "easy-pie-coming-soon" since 2018-10-01 causing problems
for plugin in iwp-client updraftplus wordfence
 do
  wp plugin install $plugin --activate
  echo
 done

# Remove identifying files to prevent hackers to know WP version
for filetodelete in readme.html olvasdel.html license.txt licenc.txt
 do
  rm -f $path/$filetodelete && echo "Deleted: $filetodelete [OK]" || echo "Could not delete: $filetodelete [FAIL]"
  echo
 done

# Import UpdraftPlus settings including Google Drive integration via SQL import
wp db import $HOME/browsumwp/plugin_updraftplus_googledrive_import.sql
echo

## ElegantThemes Divi theme installation, API key import and update to latest
echo "Trying to perform these tasks for Divi: download, install, activat, ElegantThemes API key import and Divi update to latest version"
# FYI there's a way of direct download of a file using a link which contains the authentication
# https://www.elegantthemes.com/api/api_downloads.php?api_update=1&theme=Divi&api_key=bc33d092c473b40fa80f30fa7f111251bea6037d&username=browsum
# As a backup method we can use a direct link from the browsum.com page, but then we need to update this file every now and then
wget "https://www.elegantthemes.com/api/api_downloads.php?api_update=1&theme=Divi&api_key=bc33d092c473b40fa80f30fa7f111251bea6037d&username=browsum" -O ~/browsumwp/Divi.zip
wp theme install $HOME/browsumwp/Divi.zip
#wp theme install http://divi.browsum.com/Divi.zip
wp theme activate Divi
wp db import $HOME/browsumwp/theme_divi_apikey_import.sql
#wp db query "insert into wbmstr_options (option_id, option_name, option_value, autoload) values (NULL, 'et_automatic_updates_options', 'a:2:{s:8:\"username\";s:7:\"browsum\";s:7:\"api_key\";s:40:\"bc33d092c473b40fa80f30fa7f11d\";}', 'yes');"
wp theme update Divi
echo "ElegantThemes Divi tasks finished above."
echo

## Import EZP Easy Pie Coming Soon plugin settings from SQL file, commented out since 2018-10-01 causing problems
#echo "Importing settings for EasyPie Coming Soon plugin from SQL file"
#wp db import $HOME/browsumwp/plugin_easypie_import.sql
#echo

#Copy the Browsum web .htaccess file to the /web folder
cp $HOME/browsumwp/htaccess_webroot $path/.htaccess && echo "Browsum webroot .htaccess copied [OK]" || echo "Couldn't copy Browsum webroot .htaccess [FAIL]"

#Copy the Browsum wp-admin .htaccess file to the /web/wp-admin folder
cp $HOME/browsumwp/htaccess_wp-admin $path/wp-admin/.htaccess && echo "Browsum wp-admin .htaccess copied [OK]" || echo "Couldn't copy Browsum wp-admin .htaccess [FAIL]"

## Remove WP-CLI
rm -f $HOME/wp-cli.phar && echo "WP-CLI successfully deleted from hosting [OK]" || echo "Couldn't delete WP-CLI from hosting [FAIL]"
#echo

# End of installation report
echo "$(tput setaf 2)End of install!$(tput sgr0)"
echo
exit