/* Processed by ecpg (15.18 (Debian 15.18-0+deb12u1)) */
/* These include files are added by the preprocessor */
#include <ecpglib.h>
#include <ecpgerrno.h>
#include <sqlca.h>
/* End of automatic include section */

#line 1 "app/online/cm_ol_0013.pgc"
/* @tier easy @module cm @transform common-online */
/*
 * cm_ol_0013.pgc - 체크섬(LRC) 검증 서비스 (CM_OL_0013)  [tier=easy]
 *
 * 요청의 원문(DATA) 에 대해 바이트 XOR 누적(LRC) 체크섬을 순수 로직으로
 * 계산하고, 기대값(EXPECT, 16진 2자리) 과 비교하여 일치여부(MATCH=Y/N)를
 * 응답한다. 대외 전문 무결성 검증 공통 루틴. 검증 결과는 무결성 감사
 * 이력(cm_lrc_log)에 적재하여 사후 추적을 지원한다.
 * (ATMI void SVC(TPSVCINFO*) 대응)
 */
#include <stdio.h>
#include <string.h>

#include "txcore.h"
#include "txcore_dbio.h"
#include "acq_util.h"
#include "cm_core.h"


#line 1 "/usr/include/postgresql/sqlca.h"
#ifndef POSTGRES_SQLCA_H
#define POSTGRES_SQLCA_H

#ifndef PGDLLIMPORT
#if  defined(WIN32) || defined(__CYGWIN__)
#define PGDLLIMPORT __declspec (dllimport)
#else
#define PGDLLIMPORT
#endif							/* __CYGWIN__ */
#endif							/* PGDLLIMPORT */

#define SQLERRMC_LEN	150

#ifdef __cplusplus
extern "C"
{
#endif

struct sqlca_t
{
	char		sqlcaid[8];
	long		sqlabc;
	long		sqlcode;
	struct
	{
		int			sqlerrml;
		char		sqlerrmc[SQLERRMC_LEN];
	}			sqlerrm;
	char		sqlerrp[8];
	long		sqlerrd[6];
	/* Element 0: empty						*/
	/* 1: OID of processed tuple if applicable			*/
	/* 2: number of rows processed				*/
	/* after an INSERT, UPDATE or				*/
	/* DELETE statement					*/
	/* 3: empty						*/
	/* 4: empty						*/
	/* 5: empty						*/
	char		sqlwarn[8];
	/* Element 0: set to 'W' if at least one other is 'W'	*/
	/* 1: if 'W' at least one character string		*/
	/* value was truncated when it was			*/
	/* stored into a host variable.             */

	/*
	 * 2: if 'W' a (hopefully) non-fatal notice occurred
	 */	/* 3: empty */
	/* 4: empty						*/
	/* 5: empty						*/
	/* 6: empty						*/
	/* 7: empty						*/

	char		sqlstate[5];
};

struct sqlca_t *ECPGget_sqlca(void);

#ifndef POSTGRES_ECPG_INTERNAL
#define sqlca (*ECPGget_sqlca())
#endif

#ifdef __cplusplus
}
#endif

#endif

#line 19 "app/online/cm_ol_0013.pgc"


/* 문자열 전 구간 바이트 XOR 로 LRC(종방향 중복검사) 계산 */
static unsigned char lrc_calc(const char *data, int len)
{
    unsigned char lrc = 0;
    int i;

    for (i = 0; i < len; i++)
        lrc ^= (unsigned char)data[i];

    return lrc;
}

TX_SERVICE(CM_OL_0013, ctx)
{
    /* exec sql begin declare section */
     
     
     
    
#line 36 "app/online/cm_ol_0013.pgc"
 long h_data_len ;
 
#line 37 "app/online/cm_ol_0013.pgc"
 char h_lrc [ 4 ] ;
 
#line 38 "app/online/cm_ol_0013.pgc"
 char h_match [ 4 ] ;
/* exec sql end declare section */
#line 39 "app/online/cm_ol_0013.pgc"


    char data[256];
    char expect[8];
    unsigned char lrc;
    unsigned int  exp_val = 0;
    char calc_hex[4];
    int  match;
    long logged = 0;

    tx_log(TX_LOG_INFO, "[CM_OL_0013] 체크섬 검증 서비스 진입");

    if (tx_buf_get(ctx->in, "DATA", data, sizeof(data)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[CM_OL_0013] DATA 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    lrc = lrc_calc(data, (int)strlen(data));
    snprintf(calc_hex, sizeof(calc_hex), "%02X", (unsigned int)lrc);

    /* 기대값(EXPECT)은 선택 입력: 없으면 계산만 수행 */
    if (tx_buf_get(ctx->in, "EXPECT", expect, sizeof(expect)) == TX_OK) {
        if (sscanf(expect, "%x", &exp_val) != 1) {
            tx_log(TX_LOG_WARN, "[CM_OL_0013] EXPECT 형식 오류 val=%s", expect);
            tx_return(ctx, TX_EINVAL, ctx->out);
            return;
        }
        match = ((unsigned int)lrc == (exp_val & 0xFF)) ? 1 : 0;
    } else {
        match = -1;   /* 비교 미수행 */
    }

    /* 무결성 검증 이력 적재 */
    h_data_len = (long)strlen(data);
    strncpy(h_lrc, calc_hex, sizeof(h_lrc) - 1);
    h_lrc[sizeof(h_lrc) - 1] = '\0';
    strncpy(h_match, (match < 0) ? "NA" : (match ? "Y" : "N"), sizeof(h_match) - 1);
    h_match[sizeof(h_match) - 1] = '\0';

    if (tx_begin() != TX_OK) {
        tx_log(TX_LOG_WARN, "[CM_OL_0013] tx_begin 경고");
    } else {
        { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "insert into cm_lrc_log ( data_len , lrc_hex , match_yn , chk_ts ) values ( $1  , $2  , $3  , now ( ) )", 
	ECPGt_long,&(h_data_len),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_lrc),(long)4,(long)1,(4)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_match),(long)4,(long)1,(4)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 84 "app/online/cm_ol_0013.pgc"


        if (sqlca.sqlcode != TX_SQL_OK) {
            TX_DBIO_LOG_ERR("CM_OL_0013 INSERT cm_lrc_log");
            tx_abort();
        } else {
            logged = (long)sqlca.sqlerrd[2];
            tx_commit();
        }
    }

    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "LRC", calc_hex);
    tx_buf_setlong(ctx->out, "LRCDEC", (long)lrc);
    tx_buf_setlong(ctx->out, "LOGGED", logged);
    if (match < 0) {
        tx_buf_sets(ctx->out, "MATCH", "N/A");
        tx_log(TX_LOG_INFO, "[CM_OL_0013] LRC 계산 lrc=%s (비교 미수행)", calc_hex);
    } else {
        tx_buf_sets(ctx->out, "MATCH", match ? "Y" : "N");
        tx_log(TX_LOG_INFO, "[CM_OL_0013] LRC=%s 기대=%02X 일치=%s",
               calc_hex, exp_val & 0xFF, match ? "Y" : "N");
    }
    tx_return(ctx, TX_OK, ctx->out);
}
