/*
 * Copyright (c) 2001 Tommy Bohlin <tommy@gatespace.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */
/* mkobextel.c
 */

#include <obexformat.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define MAXNAME                  24

static int ofs;
static int cr;
static int size;
static char* text;

static void addChar(int c)
{
  if(ofs>size-3) {
    size*=2;
    text=realloc(text,size);
  }
  if(c=='\n') {
    if(!cr) text[ofs++]='\r';
  } else {
    if(cr) text[ofs++]='\n';
  }
  text[ofs++]=c;
  cr= c=='\r';
}

static void addStr(const char* s)
{
  while(*s) addChar(*s++);
}

static void endInput(void)
{
  if(cr) text[ofs++]='\n';
}

int main(int argc, char** argv)
{
  int c;
  int usage=0;
  char* name=0;
  char* tel=0;
  char namebuf[MAXNAME+5];

  while((c=getopt(argc,argv,"n:t:h"))!=-1) {
    switch(c) {
    case 'n': name=optarg; break;
    case 't': tel=optarg; break;
    case 'h': usage=1; break;
    case '?': usage=1; break;
    }
  }

  if(usage || !name || !tel) {
    fprintf(stderr,"Format Nokia telephone number from stdin or command line\n");
    fprintf(stderr,"Usage: %s -n name -t tel\n",argv[0]);
    return 0;
  }

  if(strlen(name)>MAXNAME) name[MAXNAME]=0;
  strcpy(namebuf,name);
  strcat(namebuf,".vcf");

  size=1024;
  text=malloc(size);

  addStr("BEGIN:VCARD\n");
  addStr("VERSION:2.1\nN:");
  addStr(name);
  addStr("\nTEL:");
  addStr(tel);
  addStr("\nEND:VCARD\n");

  endInput();

  putName(namebuf,strlen(namebuf));
  putEndOfBody(text,ofs);

  return 0;
}
