#!/bin/bash

set -e

cur_dir="$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
proj_dir="$(realpath "$cur_dir/../..")"

SYNC_SRC="$proj_dir/src"
PROJECTS_DIR="$(realpath "$proj_dir/..")"
RED='\033[31m'
GREEN='\033[32m'
YELLOW='\033[33m'
RESET='\033[0m'

if [ -z "$1" ]; then
  read -p "Enter project: " PROJECT_SLUG
  if [ -z "$PROJECT_SLUG" ]; then
    echo "Project slug cannot be empty."
    exit 1
  fi
else
  PROJECT_SLUG="$1"
fi

case "$PROJECT_SLUG" in
    *-site|-site-legacy|-shop|-shop-legacy) ;;
    *) PROJECT_SLUG="${PROJECT_SLUG}-site";;
esac

TARGET_PROJECT_DIR="${PROJECTS_DIR}/${PROJECT_SLUG}"
if [ ! -d "${TARGET_PROJECT_DIR}" ]; then
    echo -e "${RED}Directory ${TARGET_PROJECT_DIR} does not exist, aborting.${RESET}"
    exit 1
fi

TARGET_BUNDLE_DIR="${TARGET_PROJECT_DIR}/vendor/gda/autoadmin"
TARGET_DIR="$TARGET_BUNDLE_DIR/src"

if [ ! -d "${TARGET_DIR}" ]; then
    mkdir -p "${TARGET_DIR}"
fi

TARGET_CACHE_DIR="${PROJECTS_DIR}/${PROJECT_SLUG}/var/cache"
if [ -d "${TARGET_CACHE_DIR}" ]; then
    echo -e "${GREEN}Clearing target cache.${RESET}"
    rm -rf "$TARGET_CACHE_DIR"
fi

echo -e "${YELLOW}--${RESET}"
echo -e "${YELLOW}Don't forget to install assets in the target project:${RESET}"
echo -e "${YELLOW}php bin/console assets:install --symlink${RESET}"
echo -e "${YELLOW}--${RESET}"

echo -e "${GREEN}Running sync: ./src to $TARGET_DIR${RESET}"

# https://lsyncd.github.io/lsyncd/manual/invoking/
lsyncd -delay "0.1" -nodaemon -rsync "$SYNC_SRC" "$TARGET_DIR"

if [ -d "${TARGET_BUNDLE_DIR}" ]; then
    echo -e "${GREEN}Removing linked vendor dir.${RESET}"
    rm -rf "${TARGET_BUNDLE_DIR}"
fi
