/*
	KON - Kanji ON Linux Console -
	Copyright (C) 1992, 1993 Takashi MANABE (manabe@tut.ac.jp)

	KON is free software; you can redistribute it and/or modify it
	under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	KON is distributed in the hope that it will be useful, but
	WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
	See the GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
	Modified for Big5Con by Hung-Chi Chu <hcchu@r350.ee.ntu.edu.tw>
*/

#include	"big5con.h"

u_int	wfontSize, sfontSize;
u_char	*sbFontBuff, *dbFontBuff;

static u_char	clientNumber;

void	SocketKill(int sfd)
{
	close(sfd);
	unlink(SOCKET_BASENAME);
}

int	SocketRecCommand(int fd, struct messageHeader *mh)
{
	return(read(fd, mh, sizeof(struct messageHeader)));
}

int	SocketSendCommand(int fd, char cmd)
{
	struct messageHeader mh;
	
	mh.cmd = cmd;
	mh.cno = clientNumber;
	return(write(fd, &mh, sizeof(struct messageHeader)));
}

int	SocketSearchName(struct sockaddr *sa, int fd)
{
#if defined(linux)
	struct	vt_stat vs;
#endif

	bzero(sa, sizeof(struct sockaddr));
	sa->sa_family = AF_UNIX;
#if defined(linux)
	if (ioctl(fd, VT_GETSTATE, &vs) < 0) {
		return EOF;
	}
	sprintf(sa->sa_data, "%s%d", SOCKET_BASENAME, vs.v_active);
#elif defined(__FreeBSD__)
	sprintf(sa->sa_data, "%s", SOCKET_BASENAME);
#endif
	return(0);
}

int	SocketClientOpen(void)
{
	int	s, len;
	struct	sockaddr sa;
	int	fd;

        if ((fd = open("/dev/console", O_WRONLY)) < 0)
		fd = open("/dev/console", O_RDONLY);
	SocketSearchName(&sa, fd);
	s = socket(AF_UNIX, SOCK_STREAM, 0);

#if defined(linux)
	len = sizeof(sa.sa_family) + strlen(sa.sa_data);
#elif defined(__FreeBSD__)
	len = sizeof(sa.sa_family) + strlen(sa.sa_data) + 1;
#endif
	if (connect(s, &sa, len) == -1) s = EOF;
	return(s);
}

int	SocketSendData(u_char *buff, int size, int fd)
{
	int	i;
	struct messageHeader mh;

	for (i = 0; i < size; i += BUFSIZ) {
		if ((size - i) < BUFSIZ)
			write(fd, (void *)buff, size - i);
		else
			write(fd, (void *)buff, BUFSIZ);
		SocketRecCommand(fd, &mh);
		if (mh.cmd != CHR_ACK) return(EOF);
		buff += BUFSIZ;
	}
	return(0);
}
