#!/bin/bash

CONFIG_FILE="/home/users/tracer/gitea-deb-builder/build.conf"
source "$CONFIG_FILE"

OUTPUT=$(/bin/bash /home/users/tracer/gitea-deb-builder/build.sh 2>&1)
EXIT_CODE=$?

# === Notification logic ===

# no mail at all
if [[ "$notify" == "never" ]]; then
    exit $EXIT_CODE
fi

# mail on error only
if [[ "$notify" == "error" && $EXIT_CODE -ne 0 ]]; then
    SUBJECT="[Gitea Build] Failed"
    echo "$OUTPUT" | mail -s "$SUBJECT" "$email"
    exit $EXIT_CODE
fi

# notify=error or success, but build was skipped → exit silently
if echo "$OUTPUT" | grep -q '^SKIP:'; then
    if [[ "$notify" == "error" || "$notify" == "success" ]]; then
        exit 0
    fi
fi

# notify=success: mail only on actual successful builds
if [[ "$notify" == "success" && $EXIT_CODE -eq 0 ]]; then
    SUBJECT="[Gitea Build] Success"
    echo "$OUTPUT" | mail -s "$SUBJECT" "$email"
    exit 0
fi

# notify=always
SUBJECT="[Gitea Build] Run result: $( [[ $EXIT_CODE -eq 0 ]] && echo Success || echo Failure )"
echo "$OUTPUT" | mail -s "$SUBJECT" "$email"

exit $EXIT_CODE