#!/bin/bash

DIR="$PWD"

#Defaults
if [ -f "$DIR/wp-config.php" ]; then
	echo -e "The file wp-config.php already exists."
	echo -e "What do you want to do? [ b=Create Backup | o=Overwrite | a=Abort] \c"
	read choice
	choice=$(echo -e $choice | tr '[:upper:]' '[:lower:]' | head -c 1)
	if [[ "$choice" == "b" ]]; then
		name="wp-config.php.backup$(date +'%y:%m:%d:%T')"
		mv "$DIR/wp-config.php" "$DIR/$name"
		echo -e "Would you like to add this new file to .gitignore? [Y/n] \c"
		read input
		input=$(echo -e $input | tr '[:upper:]' '[:lower:]' | head -c 1)
		if [[ $input != 'n' ]];then
			echo "$name" >> .gitignore
		fi

	fi
	if [[ "$choice" == "a" ]]; then
		echo -e "Aborted by user"
		return 1
	fi
fi

if [ ! -f "$DIR/wp-config-sample.php" ]; then
    echo "File not found!"
	echo "Downloading sample"
	curl "https://raw.githubusercontent.com/WordPress/WordPress/master/wp-config-sample.php" -o wp-config.php
fi

cp wp-config-sample.php wp-config.php


echo "Downloading Salts"
curl "https://api.wordpress.org/secret-key/1.1/salt/" -sSo salts
csplit wp-config.php '/AUTH_KEY/' '/NONCE_SALT/+1'
cat xx00 salts xx02 | tr -d '\r' > wp-config.php
rm salts xx00 xx01 xx02


echo -e "Please enter the database name \c"
read DBNAME
wp config set 'DB_NAME' "$DBNAME" > /dev/null

wp config set 'DB_USER' "root" > /dev/null
wp config set 'DB_PASSWORD' "root" > /dev/null
wp config set 'DB_HOST' "localhost" > /dev/null

wp config set 'JQUERY' "/wp-includes/js/jquery/jquery.js" --type=constant > /dev/null

echo -e "Would you like to have debug on? [y/N] \c"
read input
input=$(echo -e $input | tr '[:upper:]' '[:lower:]' | head -c 1)
if [ "$input" == "y" ]; then
	debug=true
else
	debug=false
fi


if [[ "$debug" == "true" ]] ; then
	wp config set 'WP_DEBUG' 'true' --raw --type=constant > /dev/null
	wp config set 'SAVEQUERIES' 'true' --raw --type=constant > /dev/null
else
	wp config set 'WP_DEBUG' 'false' --raw --type=constant > /dev/null
	wp config set 'SAVEQUERIES' 'false' --raw --type=constant > /dev/null
fi


# If wordpress is installed in a sub-directory, add redirects
#if [[ "$subdirectory" == "true" ]]; then
#	echo "define( 'WP_CONTENT_DIR', dirname( __FILE__ ) . '/wp-content' );" >> "$DIR/wp-config.php"
#	echo "define( 'WP_CONTENT_URL', 'http://' . \$_SERVER['HTTP_HOST'] . '/wp-content' );" >> "$DIR/wp-config.php"
#fi
#echo "if ( !defined('ABSPATH') )" >> "$DIR/wp-config.php"
#echo "    define('ABSPATH',dirname(__FILE__) . '/'); " >> "$DIR/wp-config.php"
#
#echo "require_once(ABSPATH . 'wp-settings.php');" >> "$DIR/wp-config.php"
#