/*
 * dip		A program for handling dialup IP connecions.
 *		Modem driving module.  On systems that support the
 *		dial(3) package, we (should) use that.  Otherwise,
 *		we use a very rudimentary HAYES-type dialer.
 *
 * Version:	@(#)modem.c	3.3.3	08/16/93
 *
 * Author:      Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
 *		Copyright 1988-1993 MicroWalt Corporation
 *
 *		This program 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.
 */
#include "dip.h"


/* Here are some HAYES modem commands. */
#define AT_ATTN		"+++"			/* "attention" string	*/
#define AT_RSET		"ATZ"			/* reset the modem	*/
#define AT_INIT		"ATE0 Q0 V1 X1"		/* setup for dialing	*/
#define AT_DIAL		"ATD"			/* start a dial		*/
#define AT_HANG		"ATH"			/* hang up the modem    */
#define AT_EOL		"\r"			/* AT "CRLF" mark	*/


static char	mdm_type[32];
static int	mdm_setup = 0;			/* can we do anything?	*/
static char	*mdm_init_s = AT_INIT;		/* current INIT string	*/


/* Set the desired type of modem. */
int
mdm_modem(char *modem)
{
  if (strcmp(modem, DEF_MODEM) != 0) {
	fprintf(stderr, "dip: modem: unknown modem type %s !\n", modem);
	return(-1);
  }
  strcpy(mdm_type, modem);
  mdm_setup = 1;
  if (opt_v == 1) printf("Modem set to \"%s\".\n", mdm_type);
  return(0);
}


/* Setup an INIT string for the current type of modem. */
int
mdm_init(char *text)
{
  char *s;

  if ((s = (char *) malloc(strlen(text) + 1)) == NULL) {
	fprintf(stderr, "Can't allocate memory for string");
	return(-1);
  }
  mdm_init_s = s;
  strcpy(mdm_init_s, text);
  if (opt_v == 1) printf("Modem INIT string set to \"%s\"\n", mdm_init_s);
  return(0);
}


/* Dial a phone number. */
int
mdm_dial(char *number)
{
  char buff[128];

  if (mdm_setup == 1) {
	/* Setup to dial out. */
	sprintf(buff, "%s%s", mdm_init_s, AT_EOL);
	tty_puts(buff);
	(void) sleep(1);

	/* Dial the phone number. */
	sprintf(buff, "%s%s%s", AT_DIAL, number, AT_EOL);
	tty_puts(buff);
	return(0);
  }
  return(-1);
}


int
mdm_reset(void)
{
  char buff[128];

  if (mdm_setup == 1) {
	/* Make the modem listen to us. */
	(void) sleep(1);
	tty_puts(AT_ATTN);
	(void) sleep(1);

	/* Reset the modem. */
	sprintf(buff, "%s%s", AT_RSET, AT_EOL);
	tty_puts(buff);
	(void) sleep(3);
	return(0);
  }
  return(-1);
}

int
mdm_hangup(void)
{
  char buff[128];

  if (mdm_setup == 1) {
	/* Make the modem listen to us. */
	(void) sleep(1);
	tty_puts(AT_ATTN);
	(void) sleep(1);

	/* Hang up the modem. */
	sprintf(buff, "%s%s", AT_HANG, AT_EOL);
	tty_puts(buff);
	(void) sleep(3);
	return(0);
  }
  return(-1);
}
