#!/bin/bash
#
# Collect all DLM-related logs and configuration for TS troubleshooting.
#

set -euo pipefail
shopt -s nullglob

HOSTNAME="$(hostname 2>/dev/null || echo moxa-device)"
TIMESTAMP="$(date +%Y%m%d-%H%M%S)"
WORKDIR="$(mktemp -d /tmp/dlm-logs-${HOSTNAME}-${TIMESTAMP}-XXXX)"
ARCHIVE="/tmp/dlm-logs-${HOSTNAME}-${TIMESTAMP}.tar.gz"
trap 'rm -rf "${WORKDIR}"' EXIT

echo "Working directory : ${WORKDIR}"
echo "Archive to create : ${ARCHIVE}"
echo

copy_logs_with_prefix() {
  local src_dir="$1"
  local prefix="$2"
  local dest_subdir="$3"

  if [ -d "${src_dir}" ]; then
    local files=( "${src_dir}/${prefix}"* )
    if [ ${#files[@]} -gt 0 ]; then
      echo "Collecting ${prefix}* from ${src_dir}"
      mkdir -p "${WORKDIR}/${dest_subdir}"
      cp -a "${files[@]}" "${WORKDIR}/${dest_subdir}/"
    else
      echo "No files matching ${prefix}* found in ${src_dir}"
    fi
  else
    echo "Directory not found: ${src_dir}"
  fi
}

copy_dir_if_exists() {
  local src_dir="$1"
  local dest_subdir="$2"

  if [ -d "${src_dir}" ]; then
    echo "Collecting directory ${src_dir}"
    mkdir -p "${WORKDIR}/${dest_subdir%/*}"
    cp -a "${src_dir}" "${WORKDIR}/${dest_subdir}"
  else
    echo "Directory not found: ${src_dir}"
  fi
}

echo "=== Step 1: Collect /var/log/*remote-agent-sdk* logs ==="
copy_logs_with_prefix "/var/log" "remote-agent-sdk" "var_log"

echo
echo "=== Step 2: Collect /var/log/moxa-dlm-agent/moxa-dlm-agent* logs ==="
copy_logs_with_prefix "/var/log/moxa-dlm-agent" "moxa-dlm-agent" "var_log_moxa-dlm-agent"

echo
echo "=== Step 3: Collect /etc/moxa/moxa-dlm-agent/ ==="
copy_dir_if_exists "/etc/moxa/moxa-dlm-agent" "etc_moxa"

echo
echo "=== Step 4: Collect /etc/remoteagent/ ==="
copy_dir_if_exists "/etc/remoteagent" "etc_remoteagent"

echo
echo "=== Step 5: Collect journalctl logs for moxa-dlm-agent ==="
mkdir -p "${WORKDIR}/journalctl"
journalctl -u moxa-dlm-agent --no-pager -n 50000 > "${WORKDIR}/journalctl/moxa-dlm-agent.log" 2>&1 || true
echo "Saved: journalctl/moxa-dlm-agent.log"

echo
echo "=== Step 6: Create tar.gz archive ==="
tar -C "${WORKDIR}" -czf "${ARCHIVE}" .

echo
echo "=== Done ==="
echo "Please provide this file to Moxa Support Team:"
echo "  ${ARCHIVE}"
echo
