/*
	AutoEntry 	0: No automatic entry
			1: Only different module name, auomatic entry
			2: Automatic entry     
*/

#include <libpq-fe.h>
#include "trustDB.h"

void	UpdateRepeater(struct	shm_form  recv_msg)
{
	char	sql[256];
	PGresult	*res;

	sprintf (sql, "update call_sign set rep_call ='%8.8s' , u_time = now() where call = '%8.8s';",
		recv_msg.Rep1Call, recv_msg.srcCall);

	res = PQexec(conDB, sql);

	if ((PQresultStatus(res) != PGRES_COMMAND_OK) || (PQntuples(res) == 0))
	{
		if (AutoEntry == 1)
		{
			PQclear (res);
			sprintf (sql, "select * from call_sign where rpad(substr(call,1,7),7) = '%7.7s';", 
				recv_msg.srcCall);
			res = PQexec (conDB,sql);
        		if (PQresultStatus(res) == PGRES_TUPLES_OK)
        		{
                		if (PQntuples(res) > 0)
                		{
					PQclear (res);
                        		sprintf (sql, "insert into call_sign values ('%8.8s', '%8.8s', noew(), 'A');",
                        			recv_msg.srcCall, recv_msg.Rep1Call);
					res = PQexec (conDB, sql);
                		}
        		}
		}
		else if (AutoEntry == 2)
		{
			PQclear (res);
			sprintf (sql, "insert into call_sign values ('%8.8s', '%8.8s', now(), 'A');",
				recv_msg.srcCall, recv_msg.Rep1Call);
			res = PQexec (conDB, sql);
		}
	}
	PQclear (res);
	return;
}

void	StoreRepeater(char repeater[], char trustname[])
{
	char	sql[256];
        PGresult        *res;
	
	sprintf (sql, "update repeater set trust_name = '%16.16s', u_time=now() where rep_call = '%8.8s';",
		trustname, repeater);
	res = PQexec (conDB, sql);

        if ((PQresultStatus(res) != PGRES_COMMAND_OK) || (PQntuples(res) == 0))
        {
                if (RepAutoEntry == 1)
                {
                        PQclear (res);
                        sprintf (sql, "select * from repeater where rpad(substr(rep_call,1,7),7) = '%7.7s';", 
				repeater);
                        res = PQexec (conDB,sql);
                        if (PQresultStatus(res) == PGRES_TUPLES_OK)
                        {
                                if (PQntuples(res) > 0)
                                {
                                        PQclear (res);
                                        sprintf (sql, "insert into repeater values ('%8.8s', '%16.16s', noew());",
                                        	repeater, trustname);
                                        res = PQexec (conDB, sql);
                                }
                        }
                }
                else if (RepAutoEntry == 2)
                {
                        PQclear (res);
                        sprintf (sql, "insert into repeater values ('%8.8s', '%16.16s', now());",
                        	repeater, trustname);
                        res = PQexec (conDB, sql);
                }
        }

	PQclear(res);
}

