#!/usr/bin/env bash

set -euo pipefail

TARGET_DIR="${1:-}"
EXPORT_URL="${2:-}"

if [[ -z "$TARGET_DIR" || -z "$EXPORT_URL" ]]; then
   echo "Uso: $0 <pasta_destino> <url_webservice>"
   exit 1
fi

if ! command -v curl >/dev/null 2>&1; then
   echo "Erro: curl nao encontrado."
   exit 1
fi

if ! command -v unzip >/dev/null 2>&1; then
   echo "Erro: unzip nao encontrado."
   exit 1
fi

TMP_DIR="$(mktemp -d)"
ZIP_FILE="$TMP_DIR/vitruvio_completo.zip"
EXTRACT_DIR="$TMP_DIR/extract"
PASTAS_EXPORTACAO=(Paineis Libs WebServices Processos Relatorios)

cleanup() {
   rm -rf "$TMP_DIR"
}
trap cleanup EXIT

mkdir -p "$EXTRACT_DIR"
mkdir -p "$TARGET_DIR"

echo "Baixando ZIP do webservice..."
curl -fL "$EXPORT_URL" -o "$ZIP_FILE"

echo "Validando ZIP..."
unzip -tq "$ZIP_FILE" >/dev/null

echo "Extraindo ZIP..."
unzip -qo "$ZIP_FILE" -d "$EXTRACT_DIR"

for pasta in "${PASTAS_EXPORTACAO[@]}"; do
   if [[ ! -d "$EXTRACT_DIR/$pasta" ]]; then
      echo "Erro: pasta obrigatoria nao encontrada no ZIP: $pasta"
      exit 1
   fi

done

echo "Sincronizando conteudo em $TARGET_DIR..."
for pasta in "${PASTAS_EXPORTACAO[@]}"; do
   mkdir -p "$TARGET_DIR/$pasta"

   if command -v rsync >/dev/null 2>&1; then
      rsync -a --delete "$EXTRACT_DIR/$pasta/" "$TARGET_DIR/$pasta/"
   else
      find "$TARGET_DIR/$pasta" -mindepth 1 -maxdepth 1 -exec rm -rf {} +
      cp -a "$EXTRACT_DIR/$pasta/." "$TARGET_DIR/$pasta/"
   fi

done

echo "Sincronizacao concluida com sucesso."
