/*
     This file is part of GNU Anastasis.
     Copyright (C) 2021 Anastasis SARL

     Anastasis 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, or (at your
     option) any later version.

     Anastasis 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
     General Public License for more details.

     You should have received a copy of the GNU General Public License
     along with Anastasis; see the file COPYING.  If not, write to the
     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
     Boston, MA 02110-1301, USA.
*/

/**
 * @file anastasis/src/util/pin.c
 * @brief pin conversion functions
 * @author Christian Grothoff
 */
#include "platform.h"
#include "anastasis_util_lib.h"


bool
ANASTASIS_scan_pin (const char *as,
                    unsigned long long *pin)
{
  char dummy;
  char s[16];

  if (NULL == as)
    return false;
  if (0 == strncasecmp ("A-", as, 2))
    as += 2; /* skip "A-" prefix if present */
  if (strlen (as) != 18)
    return false;
  if ( ('-' != as[5]) ||
       ('-' != as[9]) ||
       ('-' != as[14]) )
    return false;
  GNUNET_snprintf (s,
                   sizeof (s),
                   "%.5s%.3s%.4s%.3s",
                   as,
                   &as[6],
                   &as[10],
                   &as[15]);
  if (1 != sscanf (s,
                   "%llu%c",
                   pin,
                   &dummy))
  {
    GNUNET_break (0);
    return false;
  }
  return true;
}


const char *
ANASTASIS_pin2s (uint64_t pin)
{
  static char buf[22];
  char tmp[16];

  GNUNET_assert (pin < ANASTASIS_PIN_MAX_VALUE);
  GNUNET_snprintf (tmp,
                   sizeof (tmp),
                   "%015llu",
                   (unsigned long long) pin);
  GNUNET_snprintf (buf,
                   sizeof (buf),
                   "A-%.5s-%.3s-%.4s-%.3s",
                   tmp,
                   &tmp[5],
                   &tmp[8],
                   &tmp[12]);
  return buf;
}
