#!/bin/bash

function encodeURL()
{
    local -r url="${1}"

    local i=0
    local walker=''

    for ((i = 0; i < ${#url}; i++))
    do
        walker="${url:i:1}"

        case "${walker}" in
            [a-zA-Z0-9.~_-])
                printf "${walker}"
                ;;
            ' ')
                printf +
                ;;
            *)
                printf '%%%X' "'${walker}"
                ;;
        esac
    done
}
function trimString()
{
    local -r string="${1}"

    sed 's,^[[:blank:]]*,,' <<< "${string}" | sed 's,[[:blank:]]*$,,'
}
function isEmptyString()
{
    local -r string="${1}"

    if [[ "$(trimString "${string}")" = '' ]]
    then
        echo 'true'
    else
        echo 'false'
    fi
}
#Project name
 project="wp_portfolio"
 project_dir="/var/www"
#S3 info
 S3KEY="AKIAISAUYAT4BMFLKVFA"
 S3SECRET="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"
 bucket='vqode-clients-backups'
# Database credentials
 user=${MYSQL_USER}
 password=${MYSQL_PASSWORD}
 host=${MYSQL_HOST}
 db_name=${MYSQL_DATABASE}

# Email SMTP
 mail_user="bonjour@lumiiq.com"
 mail_password="dbvp7H,3D%^&s56"
 mail_host="mx.vqode.com"
 mail_port="2525"
 mail_to="ali.arshad.gem@gmail.com"

# Other options
 backup_path="/var/www/dbBackups"
 date=$(date +"%a-%d-%b-%Y-%T")
 mkdir -p $backup_path

# Set default file permissions
 umask 177

# Deleting old backups
 find $backup_path/*  -exec rm {} \;

# Dump database into SQL file
echo "Generating SQL Backup"
mysqldump --user=$user --password=$password --host=$host $db_name > $backup_path/$db_name-$date.sql

# Delete files older than 30 days
# find $backup_path/* -mtime +30 -exec rm {} \;

#make the archive
echo "Creating zip"
zip -r $project-$date.zip $project_dir/*


#Lets upload to s3
function putS3
{
  path=$1
  file=$2
  aws_path=$3
  date_aws=$(date +"%a, %d %b %Y %T %z")
  acl="x-amz-acl:private"
  content_type='application/zip'
  string="PUT\n\n$content_type\n$date_aws\n$acl\n/$bucket$aws_path$file"
  signature=$(echo -en "${string}" | openssl sha1 -hmac "${S3SECRET}" -binary | base64)
  curl -X PUT -T "$path/$file" \
    -H "Host: $bucket.s3.amazonaws.com" \
    -H "Date: $date_aws" \
    -H "Content-Type: $content_type" \
    -H "$acl" \
    -H "Authorization: AWS ${S3KEY}:$signature" \
    "https://$bucket.s3.amazonaws.com$aws_path$file"
}

echo "Uploading to S3"
putS3 "." "$project-$date.zip" "/backups/$project/"

#Lets generate signed URL
function generateSignURL()
{
    awsAccessKeyID=${S3KEY}
    awsSecretAccessKey=${S3SECRET}
    region="us-east-1"
    local -r filePath="${1}"
    local -r method="GET"
    local -r minuteExpire=2880

    if [[ "${region}" = 'us-east-1' ]]
    then
        region=''
    fi

    local -r endPoint="$("$(isEmptyString "${region}")" = 'true' && echo 's3.amazonaws.com' || echo "s3-${region}.amazonaws.com")"
    local -r expire="$(($(date +'%s') + minuteExpire * 60))"
    local -r signature="$(
        echo -en "${method}\n\n\n${expire}\n/${bucket}/${filePath}" |
        openssl dgst -sha1 -binary -hmac "${awsSecretAccessKey}" |
        openssl base64
    )"
    local -r query="AWSAccessKeyId=$(encodeURL "${awsAccessKeyID}")&Expires=${expire}&Signature=$(encodeURL "${signature}")"

    signed_url="https://${endPoint}/${bucket}/${filePath}?${query}"
}

generateSignURL "backups/$project/$project-$date.zip"

#Lets remove the zip
echo "Removing zip file"
rm $project-$date.zip

echo "Sending notification email"
body="Backup ($project-$date.zip) generated and uploaded to S3. Download link: $signed_url"
subject="$project backup generated"

(echo $body) | mailx -v -s "$subject" -S smtp-use-starttls -S smtp="$mail_host:$mail_port" -S smtp-auth="login" -S smtp-auth-user=$mail_user -S smtp-auth-password=$mail_password -S from=$mail_user $mail_to