#!/bin/sh
# 首启装完软件后回传安装日志到服务端(公开接口,首启无 JWT)。
# 参数:$1=REPORT_URL  $2=results.txt(每行 "软件名<TAB>true/false")  $3=START_TS(epoch秒)
# 单独成脚本以避开在 ObjC 字符串里做 JSON 转义;用系统自带 perl 做转义(新机无 python3)。
URL="$1"; RESF="$2"; START_TS="$3"
[ -z "$URL" ] && exit 0

SERIAL=$(ioreg -l 2>/dev/null | grep IOPlatformSerialNumber | awk -F'"' '{print $4}')
MODEL=$(sysctl -n hw.model 2>/dev/null)
OSV=$(sw_vers -productVersion 2>/dev/null)
OSB=$(sw_vers -buildVersion 2>/dev/null)
NOW=$(date +%s)
DUR=$(( NOW - ${START_TS:-$NOW} ))

# 软件结果 → JSON 数组(perl 转义软件名里的 \ 和 ")
SR=$(perl -F'\t' -lane '$n=$F[0]; $n=~s/\\/\\\\/g; $n=~s/"/\\"/g; push @a,"{\"name\":\"$n\",\"ok\":$F[1]}"; END{print "[".join(",",@a)."]"}' "$RESF" 2>/dev/null)
[ -z "$SR" ] && SR="[]"

# 完整日志 → JSON 字符串(整体转义,超大服务端会截断保留尾部)
LOGJ=$(perl -0777 -pe 's/\\/\\\\/g; s/"/\\"/g; s/\n/\\n/g; s/\t/\\t/g; s/\r//g' /var/log/1000mac-firstboot.log 2>/dev/null)

printf '{"source":"firstboot","run_mode":"desktop","install_type":"soft","mac_serial":"%s","model_identifier":"%s","mac_version":"%s","os_build":"%s","status":"completed","duration":%s,"software_results":%s,"log_text":"%s"}' \
  "$SERIAL" "$MODEL" "$OSV" "$OSB" "$DUR" "$SR" "$LOGJ" > /tmp/_firstboot_report.json

curl -s -m 15 -X POST -H "Content-Type: application/json" --data @/tmp/_firstboot_report.json "$URL" >/dev/null 2>&1 || true
