#!/usr/bin/env bash

# -------------------------------
# Defaults (can be overridden by --options)
# -------------------------------
GSDL3SRCHOME="$HOME/greenstone3-svn"

wordpress_url="https://mydomain.org/greenstone3/wordpress/"
wordpress_www_root=""   # if empty, defaults to "$GSDL3SRCHOME/web/wordpress"

wordpress_db="wordpress"
wordpress_db_prefix="wp_"
wordpress_dbuser="wp_dbuser"
wordpress_dbuser_pw="changeme"
wordpress_dbhost="localhost"

wp_sitename_title="My Site"
wp_sitename_url="https://mydomain.org/greenstone3/wordpress/"
wp_sitename_admin_un="admin"
wp_sitename_admin_pw="changeme"
wp_sitename_admin_email="you@example.org"

WP="${PWD}/bin/script/wp"   # path to wp-cli; falls back to $(command -v wp)

#NON_INTERACTIVE=0
FORCE_CREATE=0

usage() {
  cat <<'EOF'
Usage: setup-wordpress.sh [OPTIONS]

Options (double hyphen form):
  --gsdl3srchome PATH
  --wordpress-url URL
  --wordpress-www-root PATH
  --wordpress-db NAME
  --wordpress-db-prefix PREFIX
  --wordpress-user USER
  --wordpress-user-pw PASS
  --wordpress-host HOST
  --wp-sitename-title TITLE
  --wp-sitename-url URL
  --wp-sitename-admin-un USER
  --wp-sitename-admin-pw PASS
  --wp-sitename-admin-email EMAIL
  --wp-cli PATH_TO_WP
  --force   Forces the recreation of the WordPress database, without interactive confirmation
  --help    how this help

Examples:
  ./setup-wordpress.sh \
    --gsdl3srchome /opt/greenstone3 \
    --wordpress-url https://example.org/greenstone3/wordpress/ \
    --wordpress-db wpdb --wordpress-user wpuser --wordpress-user-pw secret \
    --wp-sitename-admin-un admin --wp-sitename-admin-pw secret --yes
EOF
}

# -------------------------------
# Parse long options (supports --opt value and --opt=value)
# -------------------------------
while [ $# -gt 0 ]; do
  case "$1" in
    --help)
      usage; exit 0;;
    --force)
      FORCE_CREATE=1;;
    --gsdl3srchome)            GSDL3SRCHOME="$2"; shift;;
    --gsdl3srchome=*)          GSDL3SRCHOME="${1#*=}";;
    --wordpress-url)           wordpress_url="$2"; shift;;
    --wordpress-url=*)         wordpress_url="${1#*=}";;
    --wordpress-www-root)      wordpress_www_root="$2"; shift;;
    --wordpress-www-root=*)    wordpress_www_root="${1#*=}";;
    --wordpress-db)            wordpress_db="$2"; shift;;
    --wordpress-db=*)          wordpress_db="${1#*=}";;
    --wordpress-db-prefix)     wordpress_db_prefix="$2"; shift;;
    --wordpress-db-prefix=*)   wordpress_db_prefix="${1#*=}";;
    --wordpress-user)          wordpress_dbuser="$2"; shift;;
    --wordpress-user=*)        wordpress_dbuser="${1#*=}";;
    --wordpress-user-pw)       wordpress_dbuser_pw="$2"; shift;;
    --wordpress-user-pw=*)     wordpress_dbuser_pw="${1#*=}";;
    --wordpress-host)          wordpress_dbhost="$2"; shift;;
    --wordpress-host=*)        wordpress_dbhost="${1#*=}";;
    --wp-sitename-title)       wp_sitename_title="$2"; shift;;
    --wp-sitename-title=*)     wp_sitename_title="${1#*=}";;
    --wp-sitename-url)         wp_sitename_url="$2"; shift;;
    --wp-sitename-url=*)       wp_sitename_url="${1#*=}";;
    --wp-sitename-admin-un)    wp_sitename_admin_un="$2"; shift;;
    --wp-sitename-admin-un=*)  wp_sitename_admin_un="${1#*=}";;
    --wp-sitename-admin-pw)    wp_sitename_admin_pw="$2"; shift;;
    --wp-sitename-admin-pw=*)  wp_sitename_admin_pw="${1#*=}";;
    --wp-sitename-admin-email) wp_sitename_admin_email="$2"; shift;;
    --wp-sitename-admin-email=*) wp_sitename_admin_email="${1#*=}";;
    --wp-cli)                  WP="$2"; shift;;
    --wp-cli=*)                WP="${1#*=}";;
    --*)
      echo "Unknown option: $1"; echo; usage; exit 2;;
    *)
      echo "Unexpected positional argument: $1"; echo; usage; exit 2;;
  esac
  shift
done

# Defaults derived from others
if [ -z "$wordpress_www_root" ]; then
  wordpress_www_root="${GSDL3SRCHOME}/web/wordpress"
fi

# Resolve wp-cli if the given path isn't executable
if [ ! -x "$WP" ]; then
  if command -v wp >/dev/null 2>&1; then
    WP="$(command -v wp)"
  else
    echo "Error: wp-cli not found.  Provide it via --wp-cli or put 'wp' in PATH." >&2
    exit 1
  fi
fi

confirm() {
  local prompt="${1:-Proceed}"
  if [ "$FORCE_CREATE" -eq 1 ]; then
    return 1
  fi
  read -r -p "${prompt} [y/N]: " _ans
  [ "$_ans" = "y" ] || [ "$_ans" = "Y" ]
}

echo ""
echo "****"
echo "For the WordPress HOME URL:"
echo "  $wordpress_url"
echo ""
echo "located in Apache2 web root directory:"
echo "  $wordpress_www_root"
echo ""
echo "The following settings will be used to configure the Maria SQL database:"
echo "  wordpress_db        : $wordpress_db"
echo "  wordpress_db_prefix : $wordpress_db_prefix"
echo "  wordpress_dbuser    : $wordpress_dbuser"
echo "  wordpress_dbuser_pw : $wordpress_dbuser_pw"
echo "  wordpress_dbhost    : $wordpress_dbhost"
echo "****"

echo ""
echo "****"
echo "The following settings will be used to configure a WordPress site:"
echo "  sitename_title       : $wp_sitename_title"
echo "  sitename_url         : $wp_sitename_url"
echo "  sitename_admin_un    : $wp_sitename_admin_un"
echo "  sitename_admin_pw    : $wp_sitename_admin_pw"
echo "  sitename_admin_email : $wp_sitename_admin_email"
echo "  wp-cli path          : $WP"
echo "****"
echo ""

#if ! confirm "Proceed"; then
#  echo "Quitting ..."
#  exit 1
#fi

echo "Changing (pushd) to WordPress web directory to run 'wp' setup/config commands"
pushd "$wordpress_www_root" >/dev/null || { echo "Cannot cd to $wordpress_www_root"; exit 1; }

needs_wp_db_create=1

wp_core_installed=0
if [ -f "$wordpress_www_root/wp-config.php" ]; then
  sudo -u www-data "$WP" core is-installed
  if [ $? -eq 0 ] ; then
      wp_core_installed=1
      needs_wp_db_create=0
  fi
fi


if [ "$wp_core_installed" -eq 1 ] ; then
  echo "Detected pre-existing WordPress installation: Database $wordpress_db"
  if confirm "Drop the database first?" ; then
    echo "Dropping database: $wordpress_db"
    sudo -u www-data "$WP" db drop --yes
    needs_wp_db_create=1
  fi
fi

# Create wp-config.php
sudo -u www-data \
  "$WP" core config \
  --url="$wordpress_url" \
  --dbname="$wordpress_db" \
  --dbprefix="$wordpress_db_prefix" \
  --dbuser="$wordpress_dbuser" \
  --dbpass="$wordpress_dbuser_pw" \
  --dbhost="$wordpress_dbhost" \
  --skip-check --force

if [ $needs_wp_db_create -eq 1 ] ; then
    # It's just been configured for the first time, but still needs the DB to be created
    sudo -u www-data "$WP" db create
fi

# Install site (fill in your details)
sudo -u www-data \
  "$WP" core install \
  --url="$wp_sitename_url" \
  --title="$wp_sitename_title" \
  --admin_user="$wp_sitename_admin_un" \
  --admin_password="$wp_sitename_admin_pw" \
  --admin_email="$wp_sitename_admin_email" \
  --skip-email

echo "!!!! Currently suppressing 'wp config shuffle-salts'"
# sudo -u www-data "$WP" config shuffle-salts

# Create the VIEW for Greenstone Realm Authentication
read -r -d '' sql_create_view <<'EOF'
CREATE OR REPLACE VIEW wp_user_roles AS
SELECT u.user_login AS user_name, 'administrator' AS role
  FROM wp_users u
  JOIN wp_usermeta m ON m.user_id = u.ID
 WHERE m.meta_key = 'wp_capabilities'
   AND m.meta_value LIKE '%"administrator";b:1%'
UNION ALL
SELECT u.user_login, 'editor'
  FROM wp_users u
  JOIN wp_usermeta m ON m.user_id = u.ID
 WHERE m.meta_key = 'wp_capabilities'
   AND m.meta_value LIKE '%"editor";b:1%'
UNION ALL
SELECT u.user_login, 'author'
  FROM wp_users u
  JOIN wp_usermeta m ON m.user_id = u.ID
 WHERE m.meta_key = 'wp_capabilities'
   AND m.meta_value LIKE '%"author";b:1%'
UNION ALL
SELECT u.user_login, 'contributor'
  FROM wp_users u
  JOIN wp_usermeta m ON m.user_id = u.ID
 WHERE m.meta_key = 'wp_capabilities'
   AND m.meta_value LIKE '%"contributor";b:1%'
UNION ALL
SELECT u.user_login, 'subscriber'
  FROM wp_users u
  JOIN wp_usermeta m ON m.user_id = u.ID
 WHERE m.meta_key = 'wp_capabilities'
   AND m.meta_value LIKE '%"subscriber";b:1%';
EOF

echo "****"
echo "In WordPress, setting a user to the role 'administrator' implies they"
echo "have all the other 'lower status' roles."
echo "For Realm authentication in Greenstone3, we make use of a SQL VIEW"
echo "so it is possible to query the WordPress database and get back"
echo "the explicit list of roles a user has."
echo ""
echo "Running SQL query to create (or replace) the VIEW"
echo "****"

printf '%s\n' "$sql_create_view" | sudo mysql -u root "$wordpress_db"

echo "Returning back (popd) from WordPress web directory"
popd >/dev/null
