#include <dk.h>

#include <stdio.h>

#if DK_HAVE_STDLIB_H
#include <stdlib.h>
#endif
#if DK_HAVE_STRING_H
#include <string.h>
#endif

#include <dkmem.h>
#include <dktypes.h>
#include <dksf.h>
#include <dkstream.h>



static
int
get_output_type(char *s)
{
  int back = 0;
  if(s) {
    if(strcmp(s, "gzip") == 0)  { back = 1; }
    if(strcmp(s, "bzip2") == 0) { back = 2; }
  } 
  return back;
}


static char default_output_name[] = { "test.dat" };


static
dk_stream_t *
open_file_as_stream(char *n, int t)
{
  int r = 0;
  dk_stream_t	*back = NULL;
  switch(t) {
    case 1: {
      back = dkstream_opengz(n, "w", 0, &r);
    } break;
    case 2: {
      back = dkstream_openbz2(n, "w", 0, &r);
    } break;
    default: {
      back = dkstream_openfile(n, "w", 0, &r);
    } break;
  }
  if(!back) {
    switch(r) {
      case DK_SF_SEC_WG: {
        printf("ERROR: \"%s\": Symlink in a group writeable directory!\n", n);
      } break;
      case DK_SF_SEC_WO: {
        printf("ERROR: \"%s\": Symlink in a world writeable directory!\n", n);
      } break;
      case DK_SF_SEC_OWNER: {
        printf("ERROR: \"%s\": Symlink owner is not target owner!\n", n);
      } break;
      case DK_SF_SEC_DIR: {
        printf("ERROR: \"%s\": This is a directory!\n", n);
      } break;
    }
    printf("ERROR: Failed to open output file \"%s\"!\n", n);
  }
  return back;
}


static char teststr1[] = { "This is the first test string.\n" };
static char teststr2[] = { "This is another test string.\n" };

static int exval = 0;

int main(int argc, char *argv[])
{
  dk_stream_t *os = NULL;	/* Output stream. */
  int ot = 0;			/* Output type, 0=plain, 1=gzip, 2=bzip2. */
  char *ofn = NULL;		/* Output file name. */
  if(argc > 1) {
    ot = get_output_type(argv[1]);
  }
  if(argc > 2) {
    ofn = argv[2];
  } else {
    ofn = default_output_name;
  }
  os = open_file_as_stream(ofn, ot);
  if(os) {
    if(!dkstream_puts(os, teststr1)) { exval = 1; }
    if(!dkstream_puts(os, teststr2)) { exval = 1; }
    dkstream_close(os);
  }
  exit(exval); return exval;
}

