/* 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/batch/cm_bt_0007.pgc"
/* @tier medium @module cm @transform common-batch */
/*
 * cm_bt_0007.pgc - 공통 파라미터 스냅샷 배치  [tier=medium]
 *
 * 운영 파라미터(cm_param) 전량을 커서로 읽어 키/값을 순서대로 해시에
 * 반영하여 스냅샷 해시와 버전을 산출한다. 파라미터 개수와 산출된
 * 스냅샷 버전을 리포트한다(무결성 비교용). 배치 main 엔트리 포함.
 *
 * 실행:  cm_bt_0007 <YYYYMMDD> [db@host]
 */
#include <stdio.h>
#include <stdlib.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 20 "app/batch/cm_bt_0007.pgc"


/* djb2 계열 해시 누적: 문자열을 기존 해시값에 반영 */
static unsigned long cm_hash_acc(unsigned long h, const char *s)
{
    int i;
    if (h == 0UL)
        h = 5381UL;
    for (i = 0; s[i]; i++)
        h = ((h << 5) + h) + (unsigned char)s[i];
    return h;
}

static int run_cm_bt_0007(const char *biz_date)
{
    /* exec sql begin declare section */
     
     
    
#line 36 "app/batch/cm_bt_0007.pgc"
 char h_param_key [ 32 ] ;
 
#line 37 "app/batch/cm_bt_0007.pgc"
 char h_param_val [ 64 ] ;
/* exec sql end declare section */
#line 38 "app/batch/cm_bt_0007.pgc"


    unsigned long snap = 0UL;
    long params = 0;
    long version;

    (void)biz_date;

    /* declare cur_cm_bt_0007 cursor for select param_key , coalesce ( param_val , '' ) from cm_param order by param_key */
#line 49 "app/batch/cm_bt_0007.pgc"


    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "declare cur_cm_bt_0007 cursor for select param_key , coalesce ( param_val , '' ) from cm_param order by param_key", ECPGt_EOIT, ECPGt_EORT);}
#line 51 "app/batch/cm_bt_0007.pgc"

    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("OPEN cur_cm_bt_0007");
        return TX_EDB;
    }

    for (;;) {
        { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "fetch cur_cm_bt_0007", ECPGt_EOIT, 
	ECPGt_char,(h_param_key),(long)32,(long)1,(32)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_param_val),(long)64,(long)1,(64)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 58 "app/batch/cm_bt_0007.pgc"


        if (sqlca.sqlcode == TX_SQL_NOTFOUND)
            break;
        if (sqlca.sqlcode != TX_SQL_OK) {
            TX_DBIO_LOG_ERR("FETCH cur_cm_bt_0007");
            break;
        }

        params++;
        snap = cm_hash_acc(snap, h_param_key);
        snap = cm_hash_acc(snap, h_param_val);
    }

    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "close cur_cm_bt_0007", ECPGt_EOIT, ECPGt_EORT);}
#line 72 "app/batch/cm_bt_0007.pgc"


    version = (long)(snap % 1000000UL);

    tx_log(TX_LOG_INFO,
           "[cm_bt_0007] 파라미터 스냅샷 params=%ld hash=%lu version=%06ld",
           params, snap, version);

    printf("========== 파라미터 스냅샷 [cm_bt_0007] ==========\n");
    printf("  파라미터 수 : %ld\n", params);
    printf("  스냅샷 해시 : %lu\n", snap);
    printf("  스냅샷 버전 : %06ld\n", version);
    printf("=============================================\n");

    return (params > 0) ? TX_OK : TX_FAIL;
}

int main(int argc, char **argv)
{
    const char *biz_date;
    const char *target;
    int rc;

    tx_set_loglevel(TX_LOG_INFO);

    if (argc < 2) {
        fprintf(stderr, "사용법: %s <YYYYMMDD> [db@host]\n", argv[0]);
        return 2;
    }
    biz_date = argv[1];
    target   = (argc >= 3) ? argv[2] : NULL;

    if (!date_is_valid(biz_date)) {
        fprintf(stderr, "오류: 유효하지 않은 영업일 '%s'\n", biz_date);
        return 2;
    }

    tx_log(TX_LOG_INFO, "[cm_bt_0007] 파라미터 스냅샷 배치 시작 date=%s", biz_date);

    rc = cm_dbio_connect(target);
    if (rc != TX_OK) {
        tx_log(TX_LOG_ERROR, "[cm_bt_0007] DB 접속 실패 rc=%d", rc);
        return 1;
    }

    rc = run_cm_bt_0007(biz_date);

    cm_dbio_disconnect();

    tx_log(TX_LOG_INFO, "[cm_bt_0007] 배치 종료 rc=%d(%s)", rc, tx_strerror(rc));
    return (rc == TX_OK) ? 0 : 1;
}
