/*
 * Secure X Message Passing Library v2 examples.
 *
 * (c) Alexander Vdolainen 2013-2015 <avdolainen@gmail.com>
 * (c) Alexander Vdolainen 2016 <avdolainen@zoho.com>
 *
 * libsxmp 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 3 of the License, or
 * (at your option) any later version.
 *
 * libsxmp 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.";
 *
 */

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

int exmps_getaddrs(const char *cline, char **host, char **login, int *port)
{
  int p = 0;
  char *tb = NULL, *h, *ttb;

  tb = strchr(cline, '@');
  if(!tb) return 0;

  h = strndup(cline, strlen(cline) - strlen(tb));
  if(!h) return 0;
  else p++;
  *host = h;
  tb += sizeof(char);

  if(!(ttb = strchr(tb, ':'))) h = strdup(tb);
  else h = strndup(tb, strlen(tb) - strlen(ttb));

  if(!h) return 0;
  p++; *login = h;

  if(ttb) {
    ttb += sizeof(char);
    *port = atoi(ttb);
    p++;
  }

  return p;
}

/*
 * simple function to read a password.
 */
char *exmps_getpass(const char *promt)
{
  char *pass = malloc(64);
  int fd = fileno(stdin), in = 0, c;
  struct termios tio;

  fprintf(stdout, "%s", promt);

  if(!pass) return NULL;
  else memset(pass, 0, 64);

  /* set the flag to disable echoing */
  tcgetattr(fd, &tio);
  tio.c_lflag &= ~ECHO;
  tcsetattr(fd, 0, &tio);

  /* read stupid line */
  while(in <= 64) {
    c = getchar();
    if(c == '\n') break;
    else {
      pass[in] = c;
      in++;
    }
  }

  /* enable echo again */
  tio.c_lflag |= ECHO;
  tcsetattr(fd, 0, &tio);

  return pass;
}