#!/usr/bin/env bash

set -e
set -o pipefail

LARK_BOT="${LARK_BOT_TOKEN}"

if [[ -z "$LARK_BOT" ]]; then
	echo "Error: LARK_BOT_TOKEN env var is required"
	exit 1
fi

LOG_FILE="${HOME}/dfbot.log"
exec >>"${LOG_FILE}" 2>&1

log() {
	echo "[$(date '+%F %T')] $*"
}

function json_escape() {
	printf '%s' "$1" | python3 -c 'import json,sys; print(json.dumps(sys.stdin.read()))'
}

function send_lark() {
	curl -s -X POST \
		-H "Content-Type: application/json" \
		-d "{\"msg_type\":\"text\",\"content\":{\"text\":$(json_escape "$1")}}" \
		"https://open.feishu.cn/open-apis/bot/v2/hook/${LARK_BOT}" >/dev/null || true
}

function collect_report() {
	local txt
	txt="$(hostnamectl hostname) $(date "+%F %T")"
	txt+=$'\n\n'"$(df -h)"
	txt+=$'\n\n'"---"
	txt+=$'\n\n'"$(docker system df)"
	echo "$txt"
}

log "===== 报告脚本开始 ====="

msg="$(collect_report)"
log "send report"
send_lark "$msg"

log "----- 报告脚本结束 -----"
