#include <libsmbclient.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <stdbool.h>

#define STRING_SIZE 255

char username[STRING_SIZE];
char passwd[STRING_SIZE];
char url[STRING_SIZE];

void auth_data_fn(const char *srv, 
    const char *shr,
    char *wg, int wglen, 
    char *un, int unlen,
    char *pw, int pwlen)
{
    printf("Authentication required for SERVER <%s> SHARE <%s> in WORKGROUP <%s>.\n", srv, shr, wg);
    //strncpy(wg, workgroup, wglen);
    strncpy(un, username, unlen);
    strncpy(pw, passwd, pwlen);
    printf("Returning <%s><%s>\n", un, pw);
}

int run_smbc_init(smbc_get_auth_data_fn fn, int debug) 
{
  int result;
  
  printf("Calling int smbc_init(mbc_get_auth_data_fn, int debug=<%d>)\n", debug);
  
  result = smbc_init(fn, debug);
  
  printf("Result : %d\n", result);
    
  return result;
}

int run_smbc_opendir(const char *durl)
{
  int result;
  int error;
  printf("Calling int smbc_opendir(const char *durl=<%s>)\n", durl);
  result = smbc_opendir(durl);
  error = errno;
  printf("Result : %d, errno=%d[%s]\n", result, error, strerror(error));
  return result;
}

struct smbc_dirent * run_smbc_readdir(int dh)
{
  int error;
  printf("Calling int smbc_readdir(int dh=<%d>)\n", dh);
  struct smbc_dirent * dirp = smbc_readdir(dh);
  error = errno;
  printf("Result : %p, errno=%d[%s]\n", dirp, error, strerror(error));
  
  return dirp;
}

int main(int argc, char **argv)
{
  int opt;
  int result;
  char s[STRING_SIZE];
  int dh;
  int i;
  
  strcpy(username, "");
  strcpy(passwd, "");
  strcpy(url, "");

  while ((opt = 
    getopt(argc, argv,"U:P:D:")) != EOF) {
    switch (opt) {
    case 'U':
      strcpy(username, optarg);
      break;
    case 'P':
      strcpy(passwd, optarg);
      break;
    case 'D':
      strcpy(url, optarg);
      break;
    default:
      printf("Bad opt: %s", opt);
      exit(1);
     }
  }

  SMBCCTX *context = smbc_init_context(smbc_new_context());
  smbc_setDebug(context, 4);
  smbc_set_context(context);
  
  result = run_smbc_init(auth_data_fn, 0);
  if(result < 0){
      printf("Failed smbc_init\n");
      exit(-1);
  }
  //smbc_setOptionPosixExtensions(context, true);

  dh = run_smbc_opendir(url);
  if(dh < 0){
    printf("Failed smbc_opendir\n");
    exit(-1);
  }

  struct smbc_dirent *pdirent;
  int found = 0;

  while((pdirent = run_smbc_readdir(dh)) != 0) {
    found = 1;
    printf("Found entry type <%d>, named <%s>\n", pdirent->smbc_type, pdirent->name);
  }  
}