#!/bin/bash

# Hook to allow toggling the Allow Overselling setting for Resellers to avoid potential quota errors when overselling is disabled. 
# Change is made in reseller.conf directly as the DirectAdmin API considers the absence of a setting in the API command as turning it OFF, but for the purposes of this script, we only need to change one setting so using the API should be unnecessary. 

# Note that this script will leave the overselling setting ENABLED for resellers IF the restore process is killed, aborted, or otherwise fails for any reason.

# Intended use: Configured as both `PRE - RESTORE` and `POST - RESTORE` Hook in JB5. Do not remove the exits after some if statements - these are intentional and allow the script to only perform certain actions during pre or post restore. 

set -eo pipefail 

ACCTOWNER="$(jetbackup5api -F getAccount -D "_id=${3}" | awk '/owner:/ {print $2}')"
CONFIG_FILE="/usr/local/directadmin/data/users/${ACCTOWNER}/reseller.conf"
DEBUG_LOG="/usr/local/jetapps/var/log/jetbackup5/jetbackupd.log"

[[ -z ${ACCTOWNER} ]] && { echo "Owner should never be empty. - Aborting Hook." >>${DEBUG_LOG} ; exit 0 ; }

# If statements all have exit 0 to allow the restore to proceed and not proceed with other actions in the script. Allows a single script to be used as pre and post restore. 

# Do not proceed if the user is admin
if [[ "${ACCTOWNER}" == "admin" ]]; then
    echo "[HOOKS DEBUG] User ${4} owner is 'admin' - Aborting Hook." >>${DEBUG_LOG}
    exit 0
fi

# Check if the config file exists
if [[ ! -f "$CONFIG_FILE" ]]; then
    echo "[HOOKS DEBUG] Config file not found: $CONFIG_FILE for $ACCTOWNER - Aborting Hook.." >>${DEBUG_LOG}
    exit 0
fi

if [[ -n "${8}" ]] && grep -q "^oversell=ON" "$CONFIG_FILE"; then
# Post Restore Hooks have $8 but Pre restore does not - if the status is set to 100 "Completed" - set to disable overselling. 
    echo "[HOOKS DEBUG] Running post-restore oversell=ON  to oversell=OFF for ${ACCTOWNER}" >>${DEBUG_LOG}
    sed -i 's/^oversell=ON/oversell=OFF/' "$CONFIG_FILE"
    exit 0
    else
    echo "[HOOKS DEBUG] Skipped this function during pre-restore">>${DEBUG_LOG}
fi


# Check if oversell is OFF and change it to ON
if grep -q "^oversell=OFF" "$CONFIG_FILE"; then
    sed -i 's/^oversell=OFF/oversell=ON/' "$CONFIG_FILE"
    echo "[HOOKS DEBUG] Changed oversell=OFF to oversell=ON for ${ACCTOWNER}" >>${DEBUG_LOG}
else
    echo "[HOOKS DEBUG] No change needed. oversell is already ON or not present for ${4} ${ACCTOWNER} owner." >>${DEBUG_LOG}
fi
exit 0