#!/bin/bash
set -euo pipefail

SCRIPT_PATH="$(cd "$(dirname "$0")" && pwd)"
SOURCE_REPO_DEFAULT="$HOME/Xslt"
SCRIPT_BASENAME="$(basename "$0")"

is_web_target_path() {
  case "$1" in
    /var/www/alvaroguedes.lat|/var/www/alvaroguedes.lat/*|/var/www/html|/var/www/html/*)
      return 0
      ;;
    *)
      return 1
      ;;
  esac
}

find_repo_root() {
  local candidate=$1

  while [ "$candidate" != "/" ]; do
    if [ -d "$candidate/.git" ]; then
      printf '%s\n' "$candidate"
      return 0
    fi
    candidate=$(dirname "$candidate")
  done

  return 1
}

if [ -n "${REPO_ROOT:-}" ]; then
  REPO_ROOT="$REPO_ROOT"
elif is_web_target_path "$SCRIPT_PATH" && [ -d "$SOURCE_REPO_DEFAULT/.git" ]; then
  REPO_ROOT="$SOURCE_REPO_DEFAULT"
elif REPO_ROOT=$(find_repo_root "$SCRIPT_PATH"); then
  :
elif [ -d "$SOURCE_REPO_DEFAULT/.git" ]; then
  REPO_ROOT="$SOURCE_REPO_DEFAULT"
else
  echo "Nao foi possivel localizar o repositorio Xslt." >&2
  exit 1
fi

if is_web_target_path "$SCRIPT_PATH" && is_web_target_path "$REPO_ROOT"; then
  echo "O updater nao deve usar o webroot como repositorio-fonte. Configure ~/Xslt ou REPO_ROOT." >&2
  exit 1
fi

SCRIPT_DIR="$REPO_ROOT/Sienge/1.Scripts/1.3Php_Curl_Json"
FILEMAKER_DIR="$REPO_ROOT/Sienge/5.Filemaker/XSLT"
SHARED_DIR="$REPO_ROOT/Sienge/1.Scripts/_shared"
LOCAL_SHARED_DIR="$REPO_ROOT/Sienge/1.Scripts/1.3Php_Curl_Json/_shared"
TABLES_DIR="$REPO_ROOT/Functions/Tables"

if [ -n "${DEPLOY_TARGETS:-}" ]; then
  read -r -a TARGETS <<<"$DEPLOY_TARGETS"
elif [ "$SCRIPT_PATH" = "/var/www/alvaroguedes.lat" ] || [ "$SCRIPT_PATH" = "/var/www/html" ]; then
  TARGETS=("$SCRIPT_PATH")
else
  TARGETS=(/var/www/html /var/www/alvaroguedes.lat)
fi

ROOT_FILES=(
  convert_heic_to_pdf.py
  convert_csv_to_xlsx.py
  upload_scan.php
  upload_xml.php
  upload_xls.php
  upload_heic.php
  upload_pdf.php
  executa_titulo[todos].php
  executa_titulos[todos].php
  executa_contrato[todos].php
  executa_contrato_todos.php
  executa_pedido[todos].php
  executa_nfes.php
  gerar_danfe.php
  executa_fornecedores[todos].php
  Atualizar_Github.sh
  Atualizar_Github_Remoto.sh
  Apagar_Arquivos.php
  test.pdf
  test.heic
  test.jpg
)

ROOT_DOTFILES=(
  .htaccess
)

SCRIPT_FILES=(
  run_curls_titulo[emissao][todos].php
  run_curls_titulos[todos].php
  run_curls_titulos[nfes_xml][todos].php
  run_curls_titulos[auditoria][todos].php
  run_curls_titulos[bulk][todos].php
  run_curls_titulos[inclusao][todos].php
  run_curl_titulos[execucao][todos].php
  run_curls_contrato[medicoes][todos].php
  run_curls_contrato[servicos][todos].php
  run_curls_contrato[todos].php
  run_curl_contratos[todos].php
  run_curl_contratos[auditoria][todos].php
  run_curl_pedido[itens][todos].php
  run_curl_pedido[nf][todos].php
  run_curl_pedido[todos].php
  run_curl_pedidos[todos].php
  run_curl_pedidos[auditoria][todos].php
  run_curl_pedidos[alteracao][todos].php
  run_curl_fornecedores[todos].php
)

XSLT_FILES=(
  transformTitulo[todos].xslt
  Modelo_Import_NF[NFe].xsl
  transformTitulos[Bulk][todos].xslt
  transformContrato[todos].xslt
  transformContratos[todos].xslt
  transformPedido[nf][todos].xslt
  transformPedido[itens][todos].xslt
  transformPedido[todos].xslt
  transformPedidos[todos].xslt
  transformFornecedores[todos].xslt
)

SHARED_FILES=(
  config.php
  contrato_helper.php
  sienge_helper.php
)

UPLOAD_FILES=(
  .htaccess
)

OUTPUT_FILES=(
  .htaccess
)

copy_files() {
  local source_dir=$1
  local target_dir=$2
  shift 2

  for name in "$@"; do
    if [ -e "$source_dir/$name" ]; then
      cp "$source_dir/$name" "$target_dir/"
    else
      echo "Aviso: arquivo nao encontrado, ignorando: $source_dir/$name" >&2
    fi
  done
}

cleanup_target() {
  local target=$1

  rm -f "$target/config.json"

  find "$target/uploads" -maxdepth 1 \( \
    -name 'upload_*_runtime-*.json' -o \
    -name 'apache_*_tail.log' -o \
    -name '*.log' \
  \) -delete 2>/dev/null || true

  find "$target/output" -maxdepth 1 \( \
    -name '*.log' -o \
    -name '*.tmp' -o \
    -name '*.bak' -o \
    -name '*.swp' \
  \) -delete 2>/dev/null || true
}

cd "$REPO_ROOT"
git fetch origin main
git reset --hard origin/main

CANONICAL_SCRIPT="$REPO_ROOT/Sienge/1.Scripts/1.3Php_Curl_Json/$SCRIPT_BASENAME"

if is_web_target_path "$SCRIPT_PATH" && [ "${DEPLOY_REEXECED:-0}" != "1" ]; then
  if [ -f "$CANONICAL_SCRIPT" ]; then
    export DEPLOY_REEXECED=1
    exec bash "$CANONICAL_SCRIPT" "$@"
  fi
fi

for target in "${TARGETS[@]}"; do
  install -d "$target" "$target/scripts" "$target/_shared" "$target/uploads" "$target/output"
  copy_files "$SCRIPT_DIR" "$target" "${ROOT_FILES[@]}"
  copy_files "$REPO_ROOT" "$target" "${ROOT_DOTFILES[@]}"
  copy_files "$SCRIPT_DIR" "$target/scripts" "${SCRIPT_FILES[@]}"
  copy_files "$FILEMAKER_DIR" "$target/scripts" "${XSLT_FILES[@]}"
  copy_files "$SHARED_DIR" "$target/_shared" "${SHARED_FILES[@]}"
  copy_files "$LOCAL_SHARED_DIR" "$target/_shared" upload_helper.php
  copy_files "$REPO_ROOT/uploads" "$target/uploads" "${UPLOAD_FILES[@]}"
  copy_files "$REPO_ROOT/output" "$target/output" "${OUTPUT_FILES[@]}"
  cp "$REPO_ROOT/config.json" "$target/_shared/"
  cp "$TABLES_DIR/obras_lookup.xml" "$target/scripts/"
  cleanup_target "$target"
done