#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
DEPLOY_DIR="${1:-"${ROOT_DIR}/build/deploy"}"

rm -rf "${DEPLOY_DIR}"
mkdir -p "${DEPLOY_DIR}"

copy_path() {
    local source="$1"

    if [ -e "${ROOT_DIR}/${source}" ]; then
        mkdir -p "${DEPLOY_DIR}/$(dirname "${source}")"
        cp -a "${ROOT_DIR}/${source}" "${DEPLOY_DIR}/${source}"
    fi
}

# CodeIgniter application/runtime entry points.
copy_path app
copy_path bootstrap
copy_path public
copy_path routes
copy_path vendor
copy_path composer.json
copy_path composer.lock
copy_path spark
copy_path preload.php

# Writable should exist on the server, but deploy only safe skeleton files.
mkdir -p \
    "${DEPLOY_DIR}/writable/cache" \
    "${DEPLOY_DIR}/writable/debugbar" \
    "${DEPLOY_DIR}/writable/logs" \
    "${DEPLOY_DIR}/writable/reports" \
    "${DEPLOY_DIR}/writable/session" \
    "${DEPLOY_DIR}/writable/uploads"

copy_path writable/.htaccess
copy_path writable/index.html
copy_path writable/.gitkeep
copy_path writable/cache/.gitkeep
copy_path writable/debugbar/.gitkeep
copy_path writable/logs/.gitkeep
copy_path writable/session/.gitkeep
copy_path writable/uploads/.gitkeep
copy_path writable/tcpdf_fonts

find "${DEPLOY_DIR}" -name '.DS_Store' -delete
