#!/usr/bin/env bash
# Creates pot files for each of the mu-plugins and the theme.
# WARNING: It will overwrite the existing pot file so use with caution.

# Import root .env file so we have access to $PROJECT_NAME
. .env

in_array() {
    local haystack=${1}[@]
    local needle=${2}
    for i in ${!haystack}; do
        if [[ ${i} == ${needle} ]]; then
            return 0
        fi
    done
    return 1
}

ignored_plugins=(
    "000-boxuk"
    "boxuk-base-wp-plugin"
    "flagpole"
)

location=wp-content/languages/$PROJECT_NAME.pot
iter=0
merge='';
for dir in ./wp-content/mu-plugins/* ; do

    # only for directories, and not symlinks
    if [[ -d "$dir" && ! -L "$dir" ]]; then
        # skip any plugins we are wanting to ignore
        if in_array ignored_plugins "$(basename $dir)"; then
            echo "skipping ${dir}"
            continue
        fi

        echo "Making POT file for ${dir}";

        if [[ $iter > 0 ]]; then
           merge='--merge';
        fi;

        bin/docker/wp i18n-twig make-pot $dir $location --package-name=$PROJECT_NAME --domain=$PROJECT_NAME $merge

        ((iter++))
    fi;
done

echo "Making POT file for ./wp-content/themes"

bin/docker/wp i18n-twig make-pot ./wp-content/themes $location --exclude=styleguide --package-name=$PROJECT_NAME --domain=$PROJECT_NAME --merge

# TODO: Remove the following if core WP-CLI i18n command ever adds support for symlinks. https://github.com/wp-cli/i18n-command/pull/249
echo "Making POT file for styleguide/system/library/components/blocks"

bin/docker/wp i18n-twig make-pot ./wp-content/themes $location --include=styleguide/system/library/components/blocks --exclude=styleguide/system/docs,styleguide/system/library/framework,styleguide/system/library/layouts --package-name=$PROJECT_NAME --domain=$PROJECT_NAME --merge
