#!/bin/sh

die() {
    >&2 echo "error: $@"
    exit 1
}

set -e

DIR=$(cd "$(dirname "$(readlink -f "$0")")" && pwd)

DEV_DIR="$(realpath "$DIR/../")"
STAGING_DIR="$HOME/staging"
PROD_DIR="$HOME/www"
REPO_URI=$(cat "$DEV_DIR/config.yaml" | grep ^git_repo | head -1 | awk '{print $2}')

[ "$(hostname)" = "4in1" ] || die "unexpected hostname. are you sure you're running it on the right machine?"

git push origin master

[ -d "$STAGING_DIR" ] || mkdir "$STAGING_DIR"
cd "$STAGING_DIR"

if [ ! -d .git ]; then
    git init
    git remote add origin "$REPO_URI"
    git fetch
    git checkout master
fi

git reset --hard
git pull origin master

composer install --no-dev --optimize-autoloader --ignore-platform-reqs
composer dump-autoload -o

if [ ! -d node_modules ]; then
    npm i
fi

cp "$DEV_DIR/config.yaml" .
"$DIR/static.sh" -o "$STAGING_DIR"

cd "$DIR"

TWIG_CACHE_DIR=$(grep 'skin_cache_prod_dir:' "$DEV_DIR/config.yaml" | sed 's/.*skin_cache_prod_dir: *//' | tr -d '[:space:]')
if [ -d "$TWIG_CACHE_DIR" ]; then
    find "$TWIG_CACHE_DIR" -maxdepth 1 -not -path "$TWIG_CACHE_DIR" -exec rm -rf {} +
fi

# copy staging to prod
rsync -a --delete --delete-excluded --info=progress2 "$STAGING_DIR/" "$PROD_DIR/" \
    --exclude .git \
    --exclude debug.log \
    --exclude='/log' \
    --exclude='/composer.*' \
    --exclude='/public/*/scss' \
    --exclude='/public/*/js' \
    --exclude='/public/sass.php' \
    --exclude='/public/js.php' \
    --exclude='*.sh' \
    --exclude='*.sql'
