#!/bin/bash

start=$SECONDS

input=".env"
while IFS= read -r line
do
    if [ "APP_ENV" == "${line%=*}" ]; then
        env="${line##*=}"
    elif [ "DB_DATABASE" == "${line%=*}" ]; then
        database="${line##*=}"
    elif [ "DB_USERNAME" == "${line%=*}" ]; then
        user="${line##*=}"
    elif [ "DB_PASSWORD" == "${line%=*}" ]; then
        pass="${line##*=}"
    elif [ "RSYNC_SAV" == "${line%=*}" ]; then
        rsync="${line##*=}"
    fi
done < "$input"

year=$(date +"%Y")
month=$(date +"%m")
day=$(date +"%d")
hour=$(date +"%H")
minutes=$(date +"%M")

if [ -z "$1" ]; then

	if [ -d "storage/logs/database" ];
    then
        echo "storage/logs/database/ exist"
    else
        mkdir database
    fi

    mysqldump --user="$user" --password="$pass" -B "$database" > storage/logs/database/save-"$database"-"$year""$month""$day"-"$hour""$minutes".sql

    if [ "$rsync" ]; then
        echo 'save by Rsync'
        rsync -avz --progress storage/logs/database/save-"$database"-"$year""$month""$day"-"$hour""$minutes".sql ssh $rsync
    fi

    if [ "production" == "$env" ];
    then
        echo "deploy in production"
        php artisan down
        git pull origin production

        composer install
        php artisan migrate --force
        php artisan optimize

        npm install --no-progress
        npm run prod
        php artisan up
    fi

elif [ "$1" = save-sql ]; then
    if [ -d "storage/logs/database" ];
    then
        echo "storage/logs/database/ exist"
    else
        mkdir database
    fi

    mysqldump --user="$user" --password="$pass" -B "$database" > storage/logs/database/save-"$database"-"$year""$month""$day"-"$hour""$minutes".sql

    if [ "$rsync" ]; then
        echo 'save by Rsync'
        rsync -avz --progress storage/logs/database/save-"$database"-"$year""$month""$day"-"$hour""$minutes".sql ssh $rsync
    fi

elif [ "$1" = git-prod ]; then

    if [ "production" == "$env" ];
    then
        echo "deploy in production"
        git pull origin production

        composer install
        php artisan migrate --force
        php artisan optimize
    fi

elif [ "$1" = npm ]; then

    if [ "production" == "$env" ];
    then

        npm install --no-progress
        npm run prod
    fi

elif [ "$1" = --help ]; then

    echo "save-sql"
	echo "git-prod"
	echo "npm"
	echo "all"

else
	echo "Nothing"
fi

duration=$(( SECONDS - start ))

echo "Déploiement terminé en $duration s"
