#!/bin/bash
# Afrihost - Afribackups2025
# Author: paulo.ds
# Modiefied by: juan.vz
# Date Modified: 2025-06-23

# Check if running as root
if [[ -f /usr/bin/id ]] && [[ $(/usr/bin/id -u) -eq 0 ]] && [[ -f /usr/local/cpanel/cpanel ]]; then
    :
else
    echo -e ${bldred}"\n [ ERROR ] ::  cPanel user - Permission Denied \n"${txtrst}
    exit 1
fi

set -e
grep  repository:  /root/.config/resticprofile/profiles.yaml  >/dev/null 2>&1 || { echo -e ${bldred}"\n [ ERROR ] :: Restic backups not configured on this server.\n"${txtrst} ; exit ; }
which resticprofile >/dev/null 2>&1 || { echo -e ${bldred}"\n [ ERROR ] :: Restic backups not configured on this server.\n"${txtrst} ; exit ; }

txtgrn='\e[0;32m'       # green
txtund=$(tput sgr 0 1)  # Underline
txtbld=$(tput bold)     # Bold
txtrst='\e[0m'          # Text reset
bldgrn='\e[1;32m'       # Green
bldblu='\e[1;34m'       # Blue
bldwht='\e[1;37m'       # White
bldred='\e[1;31m'       # Red
bldylw='\e[1;33m'       # Yellow
bldmag='\e[1;35m'       # Magenta
bldcyn='\e[1;36m'       # Cyan
bldgray='\e[1;30m'      # Gray

frontSP="${bldgray}-==[${txtrst}"
midSP="${bldgray}] ::${txtrst}"
backSP="${bldgray}]==-${txtrst}"


MRAN="$RAN"
restores_base_dir="/home/restic_restores"
[ -d $restores_base_dir ] || mkdir -p $restores_base_dir 2>/dev/null

TRUEUSERDOMAINS="/etc/trueuserdomains"

# get cpanel info
resolve_user() {
    local input="$1"
    local USER=""

    if [[ -f "$TRUEUSERDOMAINS" ]]; then
        USER=$(grep -E "^${input}:" "$TRUEUSERDOMAINS" | awk '{ print $2 }')
    fi

    if [[ -z "$USER" ]]; then
        USER="$input"  # Assume input is already the username
    fi

    echo "$USER"
}

# Function to check for lock and capture command output
check_lock() {
    local path="$1"
    local cmd="resticprofile snapshots -c --path /home/$USER"
    local output

    output=$(echo "$cmd" | bash 2>&1)

    if echo "$cmd" | bash  | grep -q "repository is already locked"; then
        echo -e "\n⚠️  ${bldred}Backup appears to be currently locked, please re-check in 15 minutes.\n"${txtrst}
        exit 3
    fi

    echo "$cmd"| bash
}

header_print () {
printf "\033c"
echo -e ${bldred}"\n
${bldgray}  #################################################################################
  #${bldred}       ___       _______ .______       __  .______       _______      _______. ${bldgray}#
  #${bldred}      /   \     |   ____||   _  \     |  | |   _  \     |   ____|    /       | ${bldgray}#
  #${bldred}     /  ^  \    |  |__   |  |_)  |    |  | |  |_)  |    |  |__      |   (----  ${bldgray}#
  #${bldred}    /  /_\  \   |   __|  |      /     |  | |      /     |   __|      \   \     ${bldgray}#
  #${bldred}   /  _____  \  |  |     |  |\  \----.|  | |  |\  \----.|  |____ .----)   |    ${bldgray}#
  #${bldred}  /__/     \__\ |__|     | _|  ._____||__| | _|  ._____||_______||_______/     ${bldgray}#
  #${bldred}                                                                               ${bldgray}#
  #${bldwht}                      Afrihost - Restic Restore Utility                        ${bldgray}#
  #${bldred}                                                                               ${bldgray}#
  #             ${frontSP}${bldylw} Afrires - Afrihost restic backup/restore ${backSP}                ${bldgray}#
  #${bldred}                                                                               ${bldgray}#
  #################################################################################"${txtrst}
}


usage_short () {
echo -e "\n
 ${frontSP} ${bldylw}USAGE: ${backSP}
 ${frontSP} Step 1: List available backup snapshot dates for cpanel user or domain: ${backSP}
 ${bldgrn}     # afrires list <cpuser|or|domain>${txtrst}


 ${frontSP} Step 2: Use snapshot_ID of the closest requested date and process restore: ${backSP}
 ${bldgrn}     # afrires restore <username|or|domain> [path/of/file/dir_to_restore] [snapshot_id]${txtrst}
 
 ${bldwht}     FYI: all restored data will be restored to an alternate location on this server and then can be moved to live${txtrst}

 ${bldylw}     Any questions contact server-admin\n${txtrst}

 ${frontSP} [ Manual commands ] ${backSP}
 ${bldwht}     Manual command to LIST restore points for path:${txtrst}
 ${bldblu}     # resticprofile snapshots -c --path /some/path${txtrst}
 ${bldwht}     Manual command to RUN restore from snapid:${txtrst}
 ${bldblu}     # resticprofile restore --path /home/<cpuser> --target /home/restic_restores/myrestore_"$RANDOM"/ --include /path/ofdata/to/restore --verify=true  <snapid>\n${txtrst}
 ${bldwht}     Command to list only snaps for user - with log output support ${txtrst}
 ${bldblu}     # afrires list <cpuser|or|domain>\n${txtrst}"
}

# Check usage
if [[ $# -lt 2 ]]; then
        header_print
        usage_short
        exit 1
fi

COMMAND="$1"
INPUT_USER="$2"
CPANEL_USER=$(resolve_user "$INPUT_USER")

if [[ "$CPANEL_USER" == "ERROR" || -z "$CPANEL_USER" ]]; then
        echo -e ${bldred}"[ ERROR ] Could not resolve user for input [ ERROR ] $INPUT_USER"${txtrst}
        exit 2
fi

case "$COMMAND" in
    list)
        header_print
        echo -e "\n ${frontSP}${bldcyn} PROCESSING ${midSP} Fetching snapshots for user: $CPANEL_USER"
        echo -e " ${frontSP}${bldcyn} PROCESSING ${midSP} NOTE: snapshot_id is ID column"${txtrst}
        echo -e " ${frontSP}${bldcyn} PROCESSING ${midSP} Running: resticprofile snapshots -c --path /home/\"$CPANEL_USER\" | bash"
        if [ -f /root/.config/resticprofile/profiles.yaml  ] ; then
        echo -e "${frontSP}${bldcyn}  PROCESSING ${midSP} ==== IF NO SNAPSHOTS LISTING, TRY RUN THE FOLLOWING ===="
        PUSER=$(rg  sftp  /root/.config/resticprofile/profiles.yaml | grep -o "sftp:.*@" | sort | uniq | sed 's/sftp://' | sed 's/@$//')
        pbk=$(rg  sftp  /root/.config/resticprofile/profiles.yaml  | grep -o "@.*:" | sort | uniq | sed 's/://' | sed 's/^@//')
        keyp=$(if ! ls -1 /root/.ssh/id_resbackups 2>/dev/null ; then keyp=/root/.ssh/id_rsa ; else keyp=/root/.ssh/id_resbackups ; fi )
        resmount=$(cat /root/.config/resticprofile/profiles.yaml  | grep  repository: | awk  -F ":" '{print $NF}' | sed 's/"//')
        resconstring=$(echo "sftp:${PUSER}@${pbk}:${resmount}")
        echo "restic -r "${resconstring}" --password-file /root/.config/resticprofile/.passwd snapshots -c --path /home/\"$CPANEL_USER\""
        fi
        #exec echo "resticprofile snapshots -c --path /home/$CPANEL_USER" | bash
        script -q -c "resticprofile snapshots -c --path /home/$CPANEL_USER" /dev/null 2>&1
        #echo "$SNAPSHOT_OUTPUT"
        echo
        echo -e " ${frontSP}${bldcyn} INFO ${midSP} Available database restore snapshot dates"${txtrst}
        ls -d1 /backup_nfs/mysql* 2>/dev/null || { script -q -c "resticprofile snapshots -c --path /home/mysqldumps" /dev/null 2>&1 ; }
        #ls -d1 /backup_nfs/mysql* 2>/dev/null || { echo "resticprofile snapshots -c --path /home/mysqldumps" | bash ; }
        echo
        echo -e " ${frontSP}${bldcyn} INFO ${midSP} For MySQL dumps, also check:"${txtrst}
        echo -e " ${bldgrn}     # ls -altrh /home/mysqldumps/ | grep <db_name>"${txtrst}
        echo
        echo -e " ${frontSP}${bldcyn} INFO ${midSP} Example restore commands for files/folders"${txtrst}
        echo -e " ${bldgrn}     # afrires restore $CPANEL_USER /home/$CPANEL_USER/mail/example.com/email_user <snapshot_id>"${txtrst}
        echo -e " ${bldgrn}     # afrires restore $CPANEL_USER /home/$CPANEL_USER/public_html <snapshot_id>"${txtrst}
        echo
        echo -e " ${frontSP}${bldcyn} INFO ${midSP} Example restore commands for databases"${txtrst}
        echo -e " ${bldgrn}     # resticprofile restore --path /home/mysqldumps --target ${restores_base_dir}/mysqldumps_restore_$(date +%Y%m%d)_${RANDOM}/ --include <db_name_to_restore> --verify=true <SNAPSHOT_ID>"${txtrst}
        echo
        ;;

    ll) 
        script -q -c "resticprofile snapshots -c --path /home/$CPANEL_USER" /dev/null 2>&1 | egrep -v "\-\-\-\-.*|ID.*Time" | awk -v host="$CPANEL_USER" '{$4=host; print $0}' | grep dirs || echo "No_DB_backups_start_crying"
        script -q -c "resticprofile snapshots -c --path /home/mysqldumps" /dev/null 2>&1 | egrep -v "\-\-\-\-.*|ID.*Time" | awk -v host=""$CPANEL_USER"" '{$4=host"_DBs"; print $0}' | grep system_data || echo "No_DB_backups_start_crying"
        ;;

    restore)
        header_print
        RESTORE_PATH="$3"
        SNAPSHOT_ID="$4"

        if [[ -z "$RESTORE_PATH" || -z "$SNAPSHOT_ID" ]]; then
                echo
                echo -e " ${frontSP}${bldcyn} INFO ${midSP} Usage for afrires restore: "${txtrst}
                echo -e " ${bldgrn}     # afrires restore <username|domain> <path_data_to_restore> <snapshot_id>"${txtrst}
                echo -e " ${frontSP}${bldcyn} INFO ${midSP} Example restore commands for databases"${txtrst}
                echo -e " ${bldgrn}     # resticprofile restore --path /home/mysqldumps --target ${restores_base_dir}/mysqldumps_restore_$(date +%Y%m%d)_${RANDOM}/ --include <db_name_to_restore> --verify=true <SNAPSHOT_ID>"${txtrst}
                echo
                exit 1
        fi

        echo
        echo -e " ${frontSP}${bldcyn} INFO ${midSP} To Restore snapshot $SNAPSHOT_ID for user: ${txtrst}$CPANEL_USER"${txtrst}
        cmd="resticprofile restore --path /home/$CPANEL_USER --target ${restores_base_dir}/${CPANEL_USER}_restore_`date +"%Y%m%d_%H%M%S"`/ --include $RESTORE_PATH --verify=true $SNAPSHOT_ID"
        #cmd="resticprofile restore -c --path $RESTORE_PATH --snapshot $SNAPSHOT_ID"
        echo -e " ${frontSP}${bldcyn} INFO ${midSP} Run this below command to proceed to restore data to tmp directory - then once restored move data to live"$txtrst
        echo -e " ${frontSP}${bldcyn} INFO ${midSP} Note: it's suggested for websites, move pre-existing content from live location, in order for a clean restore"${txtrst}
        echo -e " ${bldgrn}     # $cmd"${txtrst}
        echo -e " ${frontSP}${bldcyn} INFO ${midSP} The restored data will be available at ${restores_base_dir}/${CPANEL_USER}_restore_`date +"%Y%m%d_%H%M%S"` if there's data and no errors during restore"${txtrst}
        #output=$(echo # "$cmd" | bash 2>&1)

        if echo "$output" | grep -q "repository is already locked"; then
                echo -e "\n⚠️  ${bldred}Backup appears to be currently locked, please re-check in 15 minutes.\n"${txtrst}
                exit 3
        fi

        echo "$output"
        ;;

    *)
        echo -e ${bldred}"\n [ ERROR ] :: Unknown command: $COMMAND"
        usage_short
        exit 1
        ;;
esac
