#!/usr/bin/env bash
# =============================================================================
#  Dextorm — Google Cloud cost & inventory audit   (READ-ONLY)
# -----------------------------------------------------------------------------
#  Inventories your GCP resources by type/size/state and flags common waste
#  (terminated VMs, unattached persistent disks, reserved-but-unused static
#  IPs, old snapshots). Exports CSVs you can share with Dextorm.
#
#  This script ONLY READS. It never creates, modifies or deletes anything.
#
#  Cost note: accurate GCP cost needs the BigQuery Billing Export. This script
#  captures inventory + waste; we pull spend from your billing export (or a
#  read-only billing role) during the audit call.
#
#  Requirements:  gcloud SDK.  A role with read access (e.g. "Viewer").
#  Usage:         gcloud auth login   &&   gcloud config set project <id>
#                 ./dextorm-gcp-audit.sh [project-id]
#  Output:        ./dextorm-audit/<timestamp>/*.csv
#
#  (c) 2026 Dextorm · team@dextorm.com
# =============================================================================
set -euo pipefail

command -v gcloud >/dev/null || { echo "[!] gcloud SDK not found. Install Google Cloud CLI."; exit 1; }

PROJECT="${1:-$(gcloud config get-value project 2>/dev/null)}"
[ -z "${PROJECT:-}" ] && { echo "[!] No project set. Run: gcloud config set project <id>"; exit 1; }
gcloud auth list --filter=status:ACTIVE --format="value(account)" | grep -q . || { echo "[!] Not authenticated. Run: gcloud auth login (read access is enough)."; exit 1; }

TS="$(date +%Y%m%d-%H%M%S)"
OUT="./dextorm-audit/$TS"
mkdir -p "$OUT"
echo "[+] Project: $PROJECT"
echo "[+] Writing reports to $OUT  (READ-ONLY run)"

INV="$OUT/inventory.csv"; WASTE="$OUT/waste-findings.csv"
echo "type,name,zone_or_region,size_or_type,state" > "$INV"
echo "severity,type,name,location,finding,detail" > "$WASTE"

# --- Compute Engine instances (type + status) ---
echo "[*] Compute instances..."
gcloud compute instances list --project "$PROJECT" \
  --format="csv[no-heading](name,zone,machineType.basename(),status)" 2>/dev/null | \
while IFS=, read -r NAME ZONE MT STATUS; do
  [ -z "${NAME:-}" ] && continue
  echo "VM,$NAME,$ZONE,$MT,$STATUS" >> "$INV"
  if [ "$STATUS" = "TERMINATED" ]; then
    echo "medium,VM,$NAME,$ZONE,Terminated VM still bills attached disks/IPs,$MT" >> "$WASTE"
  fi
done

# --- Unattached persistent disks (users == empty) ---
echo "[*] Persistent disks..."
gcloud compute disks list --project "$PROJECT" \
  --format="csv[no-heading](name,zone.basename(),sizeGb,type.basename(),users.len())" 2>/dev/null | \
while IFS=, read -r NAME ZONE SIZE TYPE USERS; do
  [ -z "${NAME:-}" ] && continue
  echo "Disk,$NAME,$ZONE,${SIZE}GB/$TYPE,-" >> "$INV"
  if [ "${USERS:-0}" = "0" ]; then
    echo "high,Disk,$NAME,$ZONE,Unattached persistent disk — billed but unused,${SIZE}GB $TYPE" >> "$WASTE"
  fi
done

# --- Reserved static IPs not in use ---
echo "[*] Static IP addresses..."
gcloud compute addresses list --project "$PROJECT" \
  --format="csv[no-heading](name,region.basename(),address,status)" 2>/dev/null | \
while IFS=, read -r NAME REGION ADDR STATUS; do
  [ -z "${NAME:-}" ] && continue
  echo "StaticIP,$NAME,${REGION:-global},$ADDR,$STATUS" >> "$INV"
  if [ "$STATUS" = "RESERVED" ]; then
    echo "medium,StaticIP,$NAME,${REGION:-global},Reserved static IP not in use — billed,$ADDR" >> "$WASTE"
  fi
done

# --- Old snapshots (>90d) ---
echo "[*] Snapshots..."
CUTOFF="$(date -u -d '90 days ago' +%Y-%m-%d 2>/dev/null || date -u -v-90d +%Y-%m-%d)"
gcloud compute snapshots list --project "$PROJECT" \
  --filter="creationTimestamp<${CUTOFF}" \
  --format="csv[no-heading](name,diskSizeGb,creationTimestamp.date('%Y-%m-%d'))" 2>/dev/null | \
while IFS=, read -r NAME SIZE CREATED; do
  [ -z "${NAME:-}" ] && continue
  echo "medium,Snapshot,$NAME,-,Snapshot older than 90 days — review retention,${SIZE}GB ($CREATED)" >> "$WASTE"
done

echo ""
echo "[+] Done. Reports in $OUT :"
ls -1 "$OUT"
echo ""
echo "For exact spend, share your BigQuery Billing Export (or a read-only"
echo "billing role) with Dextorm (team@dextorm.com). Nothing was modified."
