#!/bin/sh

# HowTo: before use the script be sure to run the 2 step below.
# 1 - Create your ssh key pair issuing this command `ssh-keygen -t rsa`
# 2 - Copy the pub key to your remote server issuing this command `ssh-copy-id -i ~/.ssh/id_rsa.pub user@server_ip`

#current datetime
CURDATEX=`date +%d%m%y`
DIRCHK1=~/Downloads/BACKUPS-PROD/www_${CURDATEX}/
DIRCHK2=~/Downloads/BACKUPS-PROD/www_${CURDATEX}/DB_FILES/
DIRCHK3=~/Downloads/BACKUPS-PROD/www_${CURDATEX}/DB_CNF/
DIRCHK4=~/Downloads/BACKUPS-PROD/www_${CURDATEX}/LOGS/
SERVER=256.256.256.256
USER=user

#rsync info
# a = archive mode
# v = verbose
# z = compress file data during the transfer
# p = set the destination permissions to be the same as the source permissions
# e = specify the remote shell to use
#test if a dir exist
#test ! -d ~/Downloads/BACKUPS-PROD/www_${CURDATEX}/ && mkdir ~/Downloads/BACKUPS-PROD/www_${CURDATEX}/


#LOCAL BACKUP MGF

#EVERYTHING (DB SQL, FILES, and CONFIGS)
#create a local dir in your PC to store all the files
#then rsync allfile from remote to local.
if [ ! -d $DIRCHK1 ]
then
    mkdir -p $DIRCHK1
    #all files
    rsync -av -zz -e ssh $USER@$SERVER:/var/backups/ $DIRCHK1
else
    echo "Directory $DIRCHK1 exists"
fi



#DB FILES AND CONFIGS @ /var/lib/mysql and /etc/mysql
#create a local dir in your PC to store the database files
if [ ! -d $DIRCHK2 ]
then
    mkdir -p $DIRCHK2
    rsync -av -zz -e ssh $USER@$SERVER:/var/lib/mysql/ $DIRCHK2
else
    echo "Directory $DIRCHK2 exists"
fi

if [ ! -d $DIRCHK3 ]
then
    mkdir -p $DIRCHK3
    rsync -av -zz -e ssh $USER@$SERVER:/etc/mysql/ $DIRCHK3
else
    echo "Directory $DIRCHK3 exists"
fi

#mysql files


#SERVER LOGS @ /var/log/
#create a local dir in your PC to store the logs
if [ ! -d $DIRCHK4 ]
then
    mkdir -p $DIRCHK4
    #app logs
    rsync -av -zz -e ssh $USER@$SERVER:/var/log/app/ $DIRCHK4
    #fail2ban
    rsync -av -zz -e ssh $USER@$SERVER:/var/log/fail2ban.log $DIRCHK4
    #nginx
    rsync -av -zz -e ssh $USER@$SERVER:/var/log/nginx/access.log $DIRCHK4
    rsync -av -zz -e ssh $USER@$SERVER:/var/log/nginx/error.log $DIRCHK4
    #auth
    rsync -av -zz -e ssh $USER@$SERVER:/var/log/auth.log $DIRCHK4
else
    echo "Directory $DIRCHK4 exists"
fi

#EOF