#!/bin/bash
set -euo pipefail
source ./common.sh

usage() {
  cat <<EOF
Usage: $0 --list | --export [--format json|yaml]

Options:
  --list           List all containers in inventory.yaml
  --export         Export inventory.yaml to specified format
  --format FORMAT  Export format: json (default) or yaml
  --help           Show this help
EOF
}

LIST=false
EXPORT=false
FORMAT="json"

if [[ $# -eq 0 ]]; then usage; exit 1; fi

while [[ $# -gt 0 ]]; do
  case $1 in
    --list) LIST=true; shift ;;
    --export) EXPORT=true; shift ;;
    --format) FORMAT="$2"; shift 2 ;;
    -h|--help) usage; exit 0 ;;
    *) echo "Unknown option $1"; usage; exit 1 ;;
  esac
done

if [[ "$LIST" == true ]]; then
  if [[ ! -f inventory.yaml ]]; then
    echo "No inventory.yaml found."
    exit 1
  fi

  echo "📋 Inventory list:"
  awk '
  /^- id:/ {id=$2}
  /hostname:/ {h=$2}
  /ip:/ {ip=$2}
  /mac:/ {mac=$2}
  /created:/ {c=$2}
  {
    if ($1=="created:")
      printf "🆔 %-6s 🖥 %-15s 🌐 %-15s 🧬 %s 📅 %s\n", id, h, ip, mac, c
  }' inventory.yaml
  exit 0
fi

if [[ "$EXPORT" == true ]]; then
  if [[ ! -f inventory.yaml ]]; then
    echo "No inventory.yaml found."
    exit 1
  fi
  case "$FORMAT" in
    json)
      yq -o=json . inventory.yaml > inventory.json
      echo "Exported inventory.json"
      ;;
    yaml)
      cp inventory.yaml inventory-export.yaml
      echo "Exported inventory-export.yaml"
      ;;
    *)
      echo "Unknown format: $FORMAT"
      exit 1
      ;;
  esac
  exit 0
fi

usage
exit 1
