#!/bin/bash
# ============================================================================
# Script de Status - Avanzato
# ============================================================================
# Uso: bash ci/scripts/status.sh
#
# Mostra status do site, ultimos deploys e backups.
# ============================================================================

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m'

CONFIG_FILE="/var/ci/config.env"
if [ -f "$CONFIG_FILE" ]; then
    source "$CONFIG_FILE"
fi

DEPLOY_PATH="${DEPLOY_PATH:-/var/www/avanzato}"
BACKUP_PATH="${BACKUP_PATH:-/var/ci/backups}"
LOG_PATH="${LOG_PATH:-/var/ci/logs}"

echo -e "${BLUE}============================================================${NC}"
echo -e "${BLUE}  Avanzato - Status do Ambiente${NC}"
echo -e "${BLUE}============================================================${NC}"
echo ""

# Status do site
echo -e "${GREEN}SITUACAO DO SITE${NC}"
echo "  URL: ${SITE_URL:-https://avanzato.com.br}"
echo "  Caminho: $DEPLOY_PATH"
echo "  Tamanho: $(du -sh "$DEPLOY_PATH" 2>/dev/null | cut -f1 || echo 'N/A')"
echo ""

# Status do Nginx
echo -e "${GREEN}NGINX${NC}"
systemctl is-active nginx 2>/dev/null && \
    echo -e "  Status: ${GREEN}Ativo${NC}" || \
    echo -e "  Status: ${RED}Inativo${NC}"
echo ""

# Ultimo deploy
echo -e "${GREEN}ULTIMOS DEPLOYS${NC}"
if [ -f "${LOG_PATH}/last-deploy.log" ]; then
    echo "  Log: ${LOG_PATH}/last-deploy.log"
    echo "  Data: $(stat -c %y "${LOG_PATH}/last-deploy.log" | cut -d'.' -f1)"
else
    echo -e "  ${YELLOW}Nenhum deploy registrado.${NC}"
fi
echo ""

# Backups
echo -e "${GREEN}BACKUPS${NC}"
echo "  Caminho: $BACKUP_PATH"
echo "  Quantidade: $(ls "${BACKUP_PATH}"/*.tar.gz 2>/dev/null | wc -l)"
echo "  Tamanho total: $(du -sh "$BACKUP_PATH" 2>/dev/null | cut -f1 || echo '0')"
echo ""

# Ultimos logs
echo -e "${GREEN}ULTIMOS LOGS${NC}"
ls -t "${LOG_PATH}"/*.log 2>/dev/null | head -5 | while read log; do
    echo "  $(basename "$log") - $(stat -c %y "$log" | cut -d'.' -f1)"
done
echo ""

# Assets preservados
echo -e "${GREEN}ASSETS PRESERVADOS${NC}"
echo "  Caminho: ${ASSETS_PATH:-/var/ci/assets}"
echo "  Conteudo:"
ls -la "${ASSETS_PATH:-/var/ci/assets}" 2>/dev/null || echo "  (vazio)"
echo ""

echo -e "${BLUE}============================================================${NC}"
