#!/bin/bash

# v.0.0.0.1
# 23.4.2024

# scripts check wordpress site for updates and if updates avalable, updates site. Finally send notification.
# syntax:
# wp_update_site
# <path_to_dir>		- path to site direcory. Directory must exists and be acessible
# <recipient>		- email address to notify
# <custom_subject>	- optional. Custom subject text. If not defined uses default.

. ./qbashlib.sh

# Zkontroluj, zda je zadán první argument
argument_exists "$1" "<path_to_dir>"

# Zkontroluj, zda existuje adresář s instalací Wordpressu
if [ ! -d "$1" ]; then
  echo "<path_to_dir> directory '$1' not found or not accssible."
  exit 1
fi

# Zkontroluj, zda je zadán třetí argument
is_email $2
if [ $? -eq 0 ]; then
  echo "<recipient> argument '$3' is not valid email address."
  exit 1
fi

site_name=$(dir_get_name "$1")
default_subject="Update notification - $site_name"
subject=$default_subject

# Zkontroluj, zda je zadán třetí argument
if [ ! -z "$3" ]; then
  subject=$4
fi

cd $1

# Zkontrolujte aktualizace pro WordPress, pluginy a šablony
wp_core_updates=$(wp core check-update)
wp_plugin_updates=$(wp plugin list --update=available)
wp_theme_updates=$(wp theme list --update=available)

# Pokud jsou dostupné aktualizace, proveďte zálohu
if [[ -n "$wp_core_updates" ]] || [[ -n "$wp_plugin_updates" ]] || [[ -n "$wp_theme_updates" ]]; then
  
  # Proveďte všechny aktualizace
  wp_result=$(wp core update)
  wp_result="$wp_result\n$(wp plugin update --all)"
  wp_result="$wp_result\n$(wp theme update --all)"

  body="Available updates:\n$wp_core_updates\n$wp_plugin_updates\n$wp_theme_updates\n"
  body="$body Processed updates:\n$wp_result"
  #echo "$body" | mail -s "$subject" $recipient
  echo "$subject -> $2\n$body"

  echo "Updates complete."
else
  echo "No updates available."
fi