#! /bin/bash
# Afrihost - manage php things... wip
# last updated: 20250411 - p

([ -f /usr/bin/id ] && [ "$(/usr/bin/id -u)" -eq "0" ]) || { echo notroot ; exit ; }

pscript=$(basename $0)
TODAY=$(date +%Y-%m-%d)
PWDIR="/root/.preports/"$pscript""
OUTFILE=""$PWDIR"/"$(hostname).doms_php_ver_"$RANDOM".txt

# cpanel check
if ! [ -f "/usr/local/cpanel/cpanel" ]; then
       echo "No cpanel"
       exit
fi

#log environment setup /root/.preports
env_set () {
if [ ! -d "$PWDIR" ]; then
                mkdir -p "$PWDIR" ;
        else
        rm -f $PWDIR/*
fi
}
env_set


LIST_FILE="$OUTFILE"

list_docroots() {
    echo "Fetching domains and their PHP versions..."
    printf "%-40s %-50s %s\n" "DOMAIN" "DOCROOT" "PHP VERSION"
    echo "--------------------------------------------------"

#    > "$LIST_FILE"

    for userdir in /var/cpanel/userdata/*; do
        user=$(basename "$userdir")
        for domainfile in "$userdir"/*; do
            domain=$(basename "$domainfile")

            # Skip junk
            if [[ "$domain" == "main" || \
                  "$domain" == *cache* || \
                  "$domain" == *.yaml* || \
                  "$domain" == *.json || \
                  "$domain" == *.transferred || \
                  "$domain" == *_SSL* || \
                  "$domain" == *.cprapid.com ]]; then
                continue
            fi

            [[ ! -f "$domainfile" ]] && continue

            docroot=$(grep -i '^documentroot:' "$domainfile" | awk '{print $2}')
            phpversion=$(grep -i '^phpversion:' "$domainfile" | awk '{print $2}')
            pdomurl=$(echo https://$domain)
            [[ -z "$phpversion" ]] && phpversion="inherit"

            printf "%-40s %-50s %s\n" "$domain" "$docroot" "$phpversion" "$pdomurl"
            echo "$domain|$docroot|$phpversion|$pdomurl" >> "$LIST_FILE"
        done
    done

    echo
    echo "System default PHP version:"
    /usr/local/cpanel/bin/rebuild_phpconf --current | grep DEFAULT
}

reset_php_versions() {
    local dryrun="$1"

    if [[ ! -f "$LIST_FILE" ]]; then
        echo "No backup found. Run with --listdocroots first."
        exit 1
    fi

    echo "Resetting all domains to saved PHP versions..."
    [[ "$dryrun" == "true" ]] && echo "(Dry run mode — no changes will be made)"

    while IFS='|' read -r domain docroot phpversion; do
        user=$(grep -l "$domain" /var/cpanel/users/* | awk -F'/' '{print $NF}')
        if [[ -n "$user" && -n "$phpversion" ]]; then
            echo "Would run: whmapi1 php_set_vhost_versions vhost-0=$domain version=$phpversion"
            if [[ "$dryrun" != "true" ]]; then
                whmapi1 php_set_vhost_versions vhost-0=$domain version=$phpversion >/dev/null
            fi
        fi
    done < "$LIST_FILE"

    echo "Reset process ${dryrun:+(dry run)} complete."
}

reset_single_domain() {
        
    local target_domain=""

    for arg in "$@"; do
        case $arg in
            --domain=*) target_domain="${arg#*=}" ;;
        esac
    done

    if [[ -z "$target_domain" ]]; then
        echo "Missing required --domain argument."
        exit 1
    fi

    if [[ ! -f "$LIST_FILE" ]]; then
        echo "Getting new list"
        list_docroots  >/dev/null
#        exit 1
    fi

    match=$(grep "^$target_domain|" "$LIST_FILE")
    if [[ -z "$match" ]]; then
        echo "Domain '$target_domain' not found in backup list."
        exit 1
    fi

    docroot=$(echo "$match" | cut -d'|' -f2)
    phpversion=$(echo "$match" | cut -d'|' -f3)
    user=$(grep -l "$target_domain" /var/cpanel/users/* | awk -F'/' '{print $NF}')

    if [[ -z "$user" ]]; then
        echo "Could not determine cPanel user for domain: $target_domain"
        exit 1
    fi

    echo "Resetting $target_domain to PHP version: $phpversion"
    whmapi1 php_set_vhost_versions vhost-0="$target_domain" version="$phpversion"
}

list_php_versions() {
    /usr/local/cpanel/bin/rebuild_phpconf --current
}

set_php_version() {
    for arg in "$@"; do
        case $arg in
            --domain=*) DOMAIN="${arg#*=}" ;;
            --php=*) PHP="${arg#*=}" ;;
        esac
    done

    if [[ -z "$DOMAIN" || -z "$PHP" ]]; then
        echo "Missing --domain or --php option"
        exit 1
    fi

    user=$(grep -l "$DOMAIN" /var/cpanel/users/* | awk -F'/' '{print $NF}')
    if [[ -z "$user" ]]; then
        echo "Could not determine cPanel user for domain: $DOMAIN"
        exit 1
    fi

    valid=$( /usr/local/cpanel/bin/rebuild_phpconf --available | grep -w "$PHP" )
    if [[ -z "$valid" ]]; then
        echo "Invalid PHP version. Use --listphp to see available versions."
        exit 1
    fi

    echo "Setting $DOMAIN to PHP $PHP"
    whmapi1 php_set_vhost_versions vhost-0="$DOMAIN" version="$PHP"
}

list_software () {
sh  /usr/local/afribin/srv_reports/checks/site_software_list.sh
}

# --- Main Control Flow ---

case "$1" in
    --list_software_urls)
        list_software
	echo "=== Report written to $OUTFILE"
        ;;
    --listdocroots)
        list_docroots
	echo "=== Report written to $OUTFILE"
        ;;
    --resetall)
        if [[ "$2" == "--dryrun" ]]; then
            reset_php_versions "true"
        else
            reset_php_versions
        fi
        ;;
    --resetdom)
        reset_single_domain "$@"
        ;;
    --listphp)
        list_php_versions
	echo "=== Report written to $OUTFILE"
        ;;
    --set)
        set_php_version "$@"
        ;;
    *)
        echo "Usage:"
        echo "  $0 --list_software_urls            List domains, docroots, and PHP versions"
        echo "  $0 --listdocroots                  List domains, docroots, and PHP versions"
        echo "  $0 --resetall                      Reset all domains to saved PHP versions"
        echo "  $0 --resetall --dryrun             Preview reset commands without executing"
        echo "  $0 --resetdom --domain=domain.com  Reset only one domain's PHP version"
        echo "  $0 --listphp                       Show system PHP configuration"
        echo "  $0 --set --domain= --php=          Set specific domain to a PHP version"
        exit 1
        ;;
esac

