/*
 * MG_MAC.pgc - mg 모듈 서비스 MG_MAC (one service = one file).
 * Split out of the former inline mg_svr.pgc; runs on the caller's XA
 * branch (no EXEC SQL CONNECT). Advertised by mg_svr at tpsvrinit.
 */
#include "MG_MAC.h"

/* ----- service-local pure helper(s) ----- */
/* simple additive 4-hex MAC/checksum over a buffer (전문 무결성 데모). */
static void mg_checksum(const char *s, char *out /* >= 5 */)
{
    unsigned int sum = 0; int i;
    for (i = 0; s[i]; i++) sum = (sum + (unsigned char)s[i] * 31u) & 0xFFFF;
    sprintf(out, "%04X", sum);
}


/* 20. MG_MAC - 전문 MAC 계산 후 해당 전문에 반영 (무결성). */
void MG_MAC(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    char raw[512], mac[8];
    EXEC SQL BEGIN DECLARE SECTION;
    long h_id;
    char h_mac[8];
    EXEC SQL END DECLARE SECTION;

    gets_(b, T_STR3, raw, sizeof(raw));
    mg_checksum(raw, mac);
    sets_(b, T_KEY1, mac);

    h_id = getl(b, T_ID1);
    if (h_id > 0) {
        strncpy(h_mac, mac, sizeof(h_mac)-1); h_mac[sizeof(h_mac)-1] = 0;
        EXEC SQL UPDATE mg_msg_log SET mac = :h_mac WHERE msg_id = :h_id;
        if (sqlca.sqlcode < 0) { userlog("MG_MAC UPDATE FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); FAIL(b); }
    }
    OK(b);
}
