#!/bin/bash
PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
destination="/mnt/s3disk/month"
file=~/.bproc.dat
if [ ! -e "$file" ]; then
    echo "count=0" > "$file"
fi 


s3disk_check() {
r=-1;
mount > /tmp/s3disk_check.tmp
grep 's3fs on /mnt/s3disk type fuse.s3fs' /tmp/s3disk_check.tmp > /tmp/s3disk_check_res.tmp
filesize=$(ls -lh '/tmp/s3disk_check_res.tmp' | awk '{print  $5}')
if [ $filesize = 0 ]; then 
	r=0
else
	
	r=1
fi
rm /tmp/s3disk_check.tmp
rm /tmp/s3disk_check_res.tmp
return $r
}

s3disk_mount() {

if [ ! -d "/mnt/s3disk" ]; then
mkdir "/mnt/s3disk"
fi
s3disk_check
if [ $? -eq '0' ]; then
sudo s3fs $1 /mnt/s3disk -o passwd_file=/root/.passwd-s3fs -o url=http://storage.yandexcloud.net -o use_path_request_style
sleep 1
fi
}
########################################
if [ -e "$file" ]; then
ip=`wget -q -4 -O- http://icanhazip.com`
ip="${ip//./-}"
s3disk_check
if [ $? -eq '0' ]; then
rm -r /mnt/s3disk
s3disk_mount $ip
fi
s3disk_check
if [ $? -eq '1' ]; then
echo $'\e[1;32m'Baguette with the name ${bold}$ip${normal} successfully mounted !!!$'\e[0m'
	if [ ! -d "$destination" ]; then
	mkdir "$destination"
	fi
	sleep 5
	. "$file"
	(( count++ ))
	echo "count=$count" > "$file"
	/usr/bin/find $destination -type f -mtime +365 -exec rm {} \; 
	date_time=`date +"%Y-%m-%d_%H-%M"`
	sudo tar cvpzf $destination/backup_$date_time.tar.gz --exclude=/bin --exclude=/proc --exclude=/boot --exclude=/dev --exclude=/lost+found --exclude=/backup.tgz --exclude=/mnt --exclude=/sys --exclude=/swapfile --exclude=/.autorelabel /
	. "$file"
	(( count-- ))
	echo "count=$count" > "$file"
	echo $'\e[1;32m'Backup created successfully !!!$'\e[0m'
	if [ $count -lt 1 ]; then
	umount -l /mnt/s3disk 2> /tmp/s3disk_unount.tmp
	fi
	
else echo $'\e[1;31m'S3DISK NOT MOUNTED $'\e[0m'
fi
fi 


