#!/usr/bin/env bash

set -e

if [[ -n "${DEBUG}" ]]; then
    set -x
fi

app_public_dir=$1

# Add symlink from persistent files volume to application's storage public dir.
if [[ -n "${app_public_dir}" ]]; then
    echo "Application's public storage dir specified, trying to symlink from files persistent volume"

    if [[ -d "${app_public_dir}" ]]; then
        if [[ ! -L "${app_public_dir}" ]]; then
            if [[ "$(ls -A "${app_public_dir}")" ]]; then
                echo "Error: failed to symlink public storage directory to a persistent volume"
                echo "Directory ${app_public_dir} either must be empty or cannot exist"
                echo "(use files import to migrate existing public files)"
                exit 1
            # If dir is not symlink and empty, remove it and link.
            else
                echo "Empty public storage dir detected: removing and symlinking"
                rm -rf "${app_public_dir}"
                ln -sf "${FILES_DIR}/public" "${app_public_dir}"
            fi
        else
            echo "Symlink already in place"
        fi
    else
        echo "No public storage dir detected: just symlinking"
        ln -sf "${FILES_DIR}/public" "${app_public_dir}"
    fi
fi
