#!/usr/bin/env bash
# Script to create cPanel account and restore afrimove-FILE
# Created by Juan.vz
# Modified: 7 Sept 2022
#   _______       ______       __       __________  ___    _   __________       ____  _____________________  ____  ______   _____ __________  ________  ______
#  / ____/ |     / / __ \      \ \     / ____/ __ \/   |  / | / / ____/ /      / __ \/ ____/ ___/_  __/ __ \/ __ \/ ____/  / ___// ____/ __ \/  _/ __ \/_  __/
# / /    | | /| / / /_/ /  _____\ \   / /   / /_/ / /| | /  |/ / __/ / /      / /_/ / __/  \__ \ / / / / / / /_/ / __/     \__ \/ /   / /_/ // // /_/ / / /   
#/ /___  | |/ |/ / ____/  /_____/ /  / /___/ ____/ ___ |/ /|  / /___/ /___   / _, _/ /___ ___/ // / / /_/ / _, _/ /___    ___/ / /___/ _, _// // ____/ / /    
#\____/  |__/|__/_/            /_/   \____/_/   /_/  |_/_/ |_/_____/_____/  /_/ |_/_____//____//_/  \____/_/ |_/_____/   /____/\____/_/ |_/___/_/     /_/     

#########################################################################
# VARS for clouring                                                     #
#########################################################################
txtgrn='\e[0;32m'               # Normal green
txtund=$(tput sgr 0 1)          # Underline
txtbld=$(tput bold)             # Bold
txtrst='\e[0m'                  # Text reset
txtblink='\e[5m'                # Text blink
txtbreset='\e[25m'              # Text blink reset
bldgrn='\e[1;32m'               # Green
bldblu='\e[1;34m'               # Blue
bldlblu='\e[1;94m'              # Light blue
bldwht='\e[1;37m'               # White
bldred='\e[1;31m'               # Red
bldylw='\e[1;33m'               # Yellow
bldcyan='\e[1;36m'              # Cyan (Bright blue)
bldmag='\e[1;35m'               # Magenta (purple)

INFO=$(echo -e ${bldylw}"-== INFO:"${txtrst})
ENFO=$(echo -e ${bldylw}"==-"${txtrst})
USAGE="
#######################################################################
 USAGE of script:
 Restore an afrimove backup on a cPanel server
 RUN:  /usr/local/afribin/afrimove_restoreacc FILE
#######################################################################
"

# cPanel check
if ! [ -f "/usr/local/cpanel/cpanel" ]; then
       echo -e "\n$INFO ${bldred}This is not a cPanel server!\n"${txtrst}
       exit
fi


#########################################################################
# Functions                                                             #
#########################################################################

restoreBackup () {
# If /home/restore_$USER/ or /home/$USER/ exists, then end the script
if [ -d "/home/restore_$USER/" ] || [ -d "/home/$USER/" ] ; then 
        echo -e "$INFO ${bldred} /home/restore_$USER/ or /home/$USER/ exists\n$INFO ${bldred} This normally happens if the afrimove restore script is re-run multiple times...\n$INFO ${bldred} So, remove the dirs in the way and re-run the script. Here are the deets for the dir's:"${txtrst}
        ls -lad /home/restore_$USER/ /home/$USER/
        echo
        exit 1
fi

# Unpack the file
echo -e "$INFO ${bldgrn} UNPACKING BACKUP FILE... "${txtrst}
mkdir -p /home/restore_$USER/ >/dev/null
tar xvzf $FILE -C /home/restore_$USER/ >/dev/null

echo -e "$INFO ${bldgrn} FINISHED UNPACKING BACKUP FILE, CREATING CPANEL ACCOUNT... "${txtrst}

# Define domain and email address
CPUSER=$( awk -F , '{print $1}' /home/restore_$USER/home/afrimove-$USER/account_details.csv )
DOMAIN=$( awk -F , '{print $2}' /home/restore_$USER/home/afrimove-$USER/account_details.csv )
DOMAIN_IP=$( awk -F , '{print $3}' /home/restore_$USER/home/afrimove-$USER/account_details.csv )
EMAIL=$( awk -F , '{print $4}' /home/restore_$USER/home/afrimove-$USER/account_details.csv )
PLAN=$( awk -F , '{print $1}' /home/restore_$USER/home/afrimove-$USER/plan.csv )

# Now create the account from supplied info
echo "y" | /scripts/killdns $DOMAIN
whmapi1 createacct username=$CPUSER domain=$DOMAIN contactemail=$EMAIL password="\"$PASSWORD\"" cpmod=jupiter dkim=1 hasshell=1 language=en owner=magicreg mailbox_format=maildir mxcheck=auto plan=PlatinumPro spf=1 2>/dev/null

# Change ownership of /home/restore_$USER/
chown -R $CPUSER:$CPUSER /home/restore_$USER/

# Lower password strenth to account for weak user passwords (we will change this back after the restore is done)
whmapi1 setminimumpasswordstrengths mysql=1 >/dev/null

# Double check the password is changed for the user account
echo -e "$PASSWORD\n$PASSWORD" | passwd $USER >/dev/null

echo -e "$INFO ${bldgrn} CREATING DATABASES "${txtrst}

# Now create the DB's
for i in `ls -1 /home/restore_$USER/home/afrimove-$USER/databases/ | sed 's/.sql//'` ;
        do uapi --user=$CPUSER Mysql create_database name=$i ;
done 2>/dev/null

echo -e "$INFO ${bldgrn} CREATING DATABASE USERS AND GRANTS... "${txtrst}

while IFS=' ' read -r i1 i2 i3;
        do uapi --user=$USER Mysql create_user name=$i2 password="\"$i3\"" ;
done < /home/restore_$USER/home/afrimove-$USER/db_details.csv 2>/dev/null
while IFS=' ' read -r i1 i2 i3;
        do uapi --user=$USER Mysql set_privileges_on_database user=$i2 database=$i1 privileges=ALL  ;
done < /home/restore_$USER/home/afrimove-$USER/db_details.csv 2>/dev/null

# For Joomla sites (format: user,password,db_name)
while IFS=' ' read -r i1 i2 i3;
        do uapi --user=$USER Mysql create_user name=$i1 password="\"$i2\"" ;
done < /home/restore_$USER/home/afrimove-$USER/joomla_db_details.csv 2>/dev/null
while IFS=' ' read -r i1 i2 i3;
        do uapi --user=$USER Mysql set_privileges_on_database user=$i1 database=$i3 privileges=ALL  ;
done < /home/restore_$USER/home/afrimove-$USER/joomla_db_details.csv 2>/dev/null

# For Moodle sites
while IFS=' ' read -r i1 i2 i3;
        do uapi --user=$USER Mysql create_user name=$i2 password="\"$i3\"" ;
done < /home/restore_$USER/home/afrimove-$USER/moodle_db_details.csv 2>/dev/null
while IFS=' ' read -r i1 i2 i3;
        do uapi --user=$USER Mysql set_privileges_on_database user=$i2 database=$i1 privileges=ALL  ;
done < /home/restore_$USER/home/afrimove-$USER/moodle_db_details.csv 2>/dev/null

# For odd sites that use defaults.php and config.php files (format: DB_user,DB_pass,DB_name)
while IFS=' ' read -r i1 i2 i3;
        do uapi --user=$USER Mysql create_user name=$i1 password="\"$i2\"" ;
done < /home/restore_$USER/home/afrimove-$USER/odd_db_details.csv 2>/dev/null
while IFS=' ' read -r i1 i2 i3;
        do uapi --user=$USER Mysql set_privileges_on_database user=$i1 database=$i3 privileges=ALL  ;
done < /home/restore_$USER/home/afrimove-$USER/odd_db_details.csv 2>/dev/null

#mysql -u root < /home/restore_$USER/home/afrimove-$USER/cwp_migration_users.sql

echo -e "$INFO ${bldgrn} IMPORTING SQL DUMPS FOR DATABASES... "${txtrst}

# Now import the SQL dumps
for i in `ls -1 /home/restore_$USER/home/afrimove-$USER/databases/ | sed 's/.sql//'` ;
        do mysql $i < /home/restore_$USER/home/afrimove-$USER/databases/$i.sql ;
done 2>/dev/null

echo -e "$INFO ${bldgrn} RESTORING PUBLIC_HTML DIRECTORY AND ANY SITEPAD OR MOODLE SITES (this could take a while...) "${txtrst}

# Copy public_html
rsync -ahP /home/restore_$USER/home/afrimove-$USER/homedir/public_html/ /home/$USER/public_html/ >/dev/null
chown ${USER}:nobody /home/$USER/public_html/ 2>/dev/null
chown -R ${USER}. /home/$USER/public_html/* 2>/dev/null
sed -i '/AddHandler/d' /home/$USER/public_html/.htaccess 2>/dev/null

# For any SitePad sites
rsync -ahP /home/restore_$USER/home/afrimove-$USER/homedir/.sitepad/* /home/$USER/.sitepad/ >/dev/null 2>/dev/null
chown -R ${USER}. /home/$USER/.sitepad/ 2>/dev/null

# For Moodle sites (get dataroot and restore it)
DATAROOT=$( awk -F' ' '{print $4}' /home/restore_$USER/home/afrimove-$USER/moodle_db_details.csv )
echo "$DATAROOT/" > /home/restore_$USER/home/afrimove-$USER/data_root.txt
INSTALLATION_DIR=$( awk -F / '{print $4}' /home/restore_$USER/home/afrimove-$USER/data_root.txt )
mkdir -p /home/$USER/$INSTALLATION_DIR 2>/dev/null
rsync -ahW /home/restore_$USER/home/afrimove-$USER/homedir/$INSTALLATION_DIR/ /home/$USER/$INSTALLATION_DIR/ >/dev/null
chown -R $USER. /home/$USER/$INSTALLATION_DIR/ 2>/dev/null
chmod -R 777 /home/$USER/$INSTALLATION_DIR/ 2>/dev/null

echo -e "$INFO ${bldgrn} CREATING SUBDOMAINS AND RESTORE THEIR CONTENT... "${txtrst}

# Create any subdomains and copy content
for i in $( cat /home/restore_$USER/home/afrimove-$USER/subdomains.csv | awk -F[','] {'print $1'} ) ;
        do
                uapi --user=$USER SubDomain addsubdomain domain=$i rootdomain=$DOMAIN dir=$i.$DOMAIN ;
                rsync -ahP /home/restore_$USER/home/afrimove-$USER/homedir/$i.$DOMAIN/ /home/$USER/$i.$DOMAIN ;
                chown $USER:nobody /home/$USER/$i.$DOMAIN ;
                chown -R $USER. /home/$USER/$i.$DOMAIN/* ;
       done 2>/dev/null

echo -e "$INFO ${bldgrn} CREATING EMAIL ACCOUNTS AND RESTORE THEIR CONTENT... "${txtrst}

# Create email accounts and copy old hased password to new shadow file
for i in $(cat /home/restore_$USER/home/afrimove-$USER/mail_accounts.csv | awk -F[','] {'print $1'}) ;
       do /usr/local/cpanel/scripts/addpop $i P@up6w0rdafriRp ;
done 2>/dev/null
cat /home/restore_$USER/home/afrimove-$USER/mail_accounts.csv | sort | awk -F[','] {'print $4,$2'} | sed 's/ {SHA512-CRYPT}/:/' > /home/$USER/etc/$DOMAIN/shadow_cwp_restore 2>/dev/null
#LASTCHANGED=$( cat /home/$USER/etc/$DOMAIN/shadow | awk -F[':'] {'print $3'} | sort -u )
cat /home/$USER/etc/$DOMAIN/shadow_cwp_restore | while read pwds ;
        do echo "$pwds:13012::::::" ;
done > /home/$USER/etc/$DOMAIN/shadow 2>/dev/null

# Now sync mails
rsync -avhP /home/restore_$USER/home/afrimove-$USER/homedir/mail/ /home/$USER/mail/$DOMAIN/ >/dev/null
chmod -R 751 /home/$USER/mail/$DOMAIN/ 2>/dev/null
chown -R $USER. /home/$USER/mail/$DOMAIN/ 2>/dev/null

# Now create the forwarders/aliases
cat /home/restore_$USER/home/afrimove-$USER/mail_aliases.csv | awk -F['|'] {'print $1,$2'} | while read fwd_address fwd_goto ;
        do echo $fwd_address: $fwd_goto >> /etc/valiases/$DOMAIN ;
done 2>/dev/null

# Check if there are any filters
# (CWP uses roundcube.sieve files for filters location at /var/vmail/<DOMAIN>/<EMAIL_USER>/sieve/roundcube.sieve)
# Just backing them up on the restore, they need to be recreated manually on cPanel

echo -e "$INFO ${bldgrn} CREATING FTP ACCOUNTS... "${txtrst}

# Now create FTP accounts
cat /home/restore_$USER/home/afrimove-$USER/ftp_details.csv | sed -e "s#/home/$USER/##" | while read ftp_user ftp_pass ftp_homedir ;
        do uapi --user=$USER Ftp add_ftp user=$ftp_user pass=6e1dxFaTDfyP homedir=$ftp_homedir quota=2000 ;
        FIND1=$( cat /etc/proftpd/$USER | grep $ftp_user | awk -F[':'] {'print $1'} | sort -u )
        FIND2=$( cat /etc/proftpd/$USER | grep $ftp_user | awk -F[':'] {'print $2'} | sort -u )
        FIND3=$( cat /etc/proftpd/$USER | grep $ftp_user | awk -F[':'] {'print $3'} | sort -u )
        FIND4=$( cat /etc/proftpd/$USER | grep $ftp_user | awk -F[':'] {'print $4'} | sort -u )
        FIND5=$( cat /etc/proftpd/$USER | grep $ftp_user | awk -F[':'] {'print $5'} | sort -u )
        FIND6=$( cat /etc/proftpd/$USER | grep $ftp_user | awk -F[':'] {'print $6'} | sort -u )
        FIND7=$( cat /etc/proftpd/$USER | grep $ftp_user | awk -F[':'] {'print $7'} | sort -u ) 
        cat /home/restore_$USER/home/afrimove-$USER/ftp_details.csv | while read fuser fpwds fdir ;
        do echo "$FIND1:$fpwds:$FIND3:$FIND4:$FIND5:$FIND6:$FIND7" ;
done >> /etc/proftpd/$USER ; # I see both accounts stay...
done 2>/dev/null
}
#restoreBackup


fix_perms () {
# Do a final chown for /home/USER_NAME/public_html/.well-known/ sake and for AutoSSL validation
echo -e "$INFO ${bldgrn} FIXING PERMISSIONS... "${txtrst}
chown -R $USER. /home/$USER/public_html/.well-known/
cd /home/$USER/
find /home/$USER/ -type f -exec chmod 644 {} \;
find /home/$USER/ -type d -exec chmod 755 {} \;
#find /home/$USER/$INSTALLATION_DIR/ -type d -exec chmod 777 {} \;
cd /home/$USER/public_html/
find . -type f -name \*.php ! -perm 640 -exec chmod 640 {} \;
find . -type f  ! -name \*.php  ! -perm 644 -exec chmod  644 {} \;
find . -type d -exec chmod 755 {} \;

chmod 750 ../public_html/

/scripts/mailperm $USER

cd /home/$USER/public_html/
find . -type d -exec chmod 755 {} \;
find . -type f -exec chmod 644 {} \;
cd
}
#fix_perms 2>/dev/null


set_things_back () {
# Set password strength back to normal
whmapi1 setminimumpasswordstrengths mysql=50 >/dev/null

# Set a newer PHP version
whmapi1 php_set_vhost_versions vhost-0=$DOMAIN version=ea-php70
}
#set_things_back >/dev/null


compose_details () {
#echo "Account details:" >> /home/restore_$USER/home/afrimove-$USER/telgm
#cat /home/restore_$USER/home/afrimove-$USER/account_details.csv >> /home/restore_$USER/home/afrimove-$USER/telgm
#echo "===========================" >> /home/restore_$USER/home/afrimove-$USER/telgm
#echo "Databases:" >> /home/restore_$USER/home/afrimove-$USER/telgm
#ls -1 /home/restore_$USER/home/afrimove-$USER/databases/ >> /home/restore_$USER/home/afrimove-$USER/telgm
#echo "===========================" >> /home/restore_$USER/home/afrimove-$USER/telgm
#echo "DB details:" >> /home/restore_$USER/home/afrimove-$USER/telgm
#cat /home/restore_$USER/home/afrimove-$USER/db_details.csv >> /home/restore_$USER/home/afrimove-$USER/telgm
#echo "===========================" >> /home/restore_$USER/home/afrimove-$USER/telgm
#echo "Joomla DB details:" >> /home/restore_$USER/home/afrimove-$USER/telgm
#cat /home/restore_$USER/home/afrimove-$USER/joomla_db_details.csv >> /home/restore_$USER/home/afrimove-$USER/telgm
#echo "===========================" >> /home/restore_$USER/home/afrimove-$USER/telgm
#echo "Moodle DB details:" >> /home/restore_$USER/home/afrimove-$USER/telgm
#cat /home/restore_$USER/home/afrimove-$USER/moodle_db_details.csv >> /home/restore_$USER/home/afrimove-$USER/telgm
echo "===========================" >> /home/restore_$USER/home/afrimove-$USER/telgm
echo "CPANEL URL: https://$HOSTNAME:2083 or http://cpanel.$DOMAIN" >> /home/restore_$USER/home/afrimove-$USER/telgm
echo "USERNAME: $CPUSER " >> /home/restore_$USER/home/afrimove-$USER/telgm
echo "DOMAIN:  $DOMAIN " >> /home/restore_$USER/home/afrimove-$USER/telgm
echo "CPANEL PASSWORD: $PASSWORD " >> /home/restore_$USER/home/afrimove-$USER/telgm
}
#compose_details


runAutoSSL () {
echo -e "$INFO ${bldgrn} CHECK AUTO-SSL ${bldred}(THIS WILL FAIL IF DNS NOT POINTING TO THIS SERVER!)${txtrst} "
echo -e "$INFO ${bldgrn} If that is the case, run:${txtrst} /usr/local/cpanel/bin/autossl_check --user=$USER "

# Now do AutoSSL
/usr/local/cpanel/bin/autossl_check --user=$USER >/dev/null
}
#runAutoSSL


cleanUp () {
echo -e "$INFO ${bldgrn} REMOVING WORKING FILES FROM UNPACKING LOCATION... \n"${txtrst}

# Clean up working files
/bin/rm -R /home/restore_$USER/

# Change to the correct Plan
whmapi1 --output=jsonpretty changepackage user=$CPUSER pkg=$PLAN
}
#cleanUp


# Show info to send to client
showInfo () {
echo -e "${bldylw}-================================================================-${txtrst}
${bldmag}-== RESTORE FINISHED - THE FOLLOWING IS INFO ABOUT THE RESTORE ${txtrst}
${bldmag}- Current DB's:${txtrst} $(mysql -e "show databases;" | grep $USER | sed ':a;N;$!ba;s/\n/ /g')"
echo -e "
${bldmag}- GRANTS for $USER@localhost:"${txtrst}
mysql -e "show grants for '$USER'@'localhost'";
echo -e "
$INFO ${bldred}Dubble check that the DB users were created.${txtrst}
$INFO ${bldred}Any filters from CWP will be located in /home/$USER/mail/$DOMAIN/<EMAIL_USER>/sieve/${txtrst}
$INFO ${bldred}You can add these manually from the above file.${txtrst}
${bldylw}-================================================================-${txtrst}

$INFO ${bldmag}RESTORE COMPLETE. Send this to the client please.
- DOMAIN:  $DOMAIN
- CPANEL URL: https://$HOSTNAME:2083 or http://cpanel.$DOMAIN
- USERNAME: $CPUSER 
- CPANEL PASSWORD: $PASSWORD "${txtrst}

echo -e "\n$INFO ${bldred}Once the domain is setup and you are happy all was re-created correctly, please run this to clean up:
- /usr/local/afribin/maintenance/graveyard_sendcpmove
"${txtrst}
}
#showInfo


# Send a telegram
send_telgrm () {
#telegram-send "CWP backup restored for $USER on $HOSTNAME"

# Juan BOT
DATE_EXEC=$( date "+%d %b %Y %H:%M" )

MESSAGE=$( echo -e "
-===-
 CWP backup restored - $DATE_EXEC
-===-
- $FILE restored
- $DOMAIN ($USER)
- On $HOSTNAME

$(cat /home/restore_$USER/home/afrimove-$USER/telgm) ")

TOKEN="1528013176:AAFTxhRPrQlvA8VI45X9hpvGYsm14Nc47Rg"
CHAT_ID="876550142"
URL="https://api.telegram.org/bot$TOKEN/sendMessage"

curl -s -X POST $URL -d chat_id=$CHAT_ID -d text="$MESSAGE"
}
#send_telgrm >/dev/null


# Check we've been given a file and run stuff if so. If not, then exit and show usage.
if test -z "$1"; then
        echo -e "\n$INFO ${bldred}No file to restore. Please provide a /home/afrimove-CWP_USERNAME.tar.gz file te restore from."${txtrst}
echo "$1"
        echo -e ${bldred}"$USAGE"${txtrst}
        exit
fi

# If we are given other orguments after the file, exit and show usage.
if ! test -z "$2" ; then
        echo -e "\n$INFO ${bldred}Do not run with other options after the file to restore, please."${txtrst}
        echo -e ${bldred}"$USAGE"${txtrst}
        exit
fi


if echo "$1" | grep afrimove >/dev/null ; then
        FILE=$1
        # If file is in /home/.graveyardtmp/, move it to /home/ first
        SEEKER=$(echo "$FILE" | awk -F"-" {'print $NF'})
        find /home/.graveyardtmp/ | grep "$SEEKER" | while read file ; do mv "$file" /home/ ; done
        # Check if file exists
        cd /home/
        if [ -f "$FILE" ]; then
                echo -e "\n$INFO ${bldgrn}You provided file $FILE and it exists, so proceeding to restore..."${txtrst}
                echo -e "$INFO ${bldgrn}Determining username and generating random password for restore..."${txtrst}
                USER=$(echo "$FILE" | grep "afrimove-.*.tar.gz" | awk -F"-" {'print $2'} | sed 's#afrimove-##g; s#.tar.gz##g')
                PASSWORD=$(< /dev/urandom tr -dc A-Z-a-z-0-9 | head -c${3:-18})
                echo -e "  - FILE: $FILE\n  - USERNAME: $USER\n  - PASSWORD: $PASSWORD\n"
                
#        echo "JUAN EXIT"
#        exit        
                # Run functions in this order
                restoreBackup
                fix_perms 2>/dev/null
                set_things_back >/dev/null
                compose_details
                runAutoSSL
                send_telgrm >/dev/null
                cleanUp
                showInfo
        
        else
                echo -e ${bldred}"\n$INFO ${bldred}$FILE does not exist in /home/."${txtrst}
                echo -e ${bldred}"$USAGE"${txtrst}
                exit
        fi
else
        echo -e "\n$INFO ${bldred}$1 is not an afrimove file."${txtrst}
        echo -e ${bldred}"$USAGE"${txtrst}
        exit

fi

exit 0
