/* pwgen - password generator
 *
 *      generates passwords with the given length
 *
 *      This program 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 2 of the License, or
 *      (at your option) any later version.
 *
 *      This program 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 this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */

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

#define CHAR_LIST "ABCDEFGHIJKLMNOPQRSTUVWXYZ"\
                  "abcdefghijklmnopqrstuvwxyz"\
                  "0123456789"

char *pw=NULL;

char *pwgen(const unsigned int size)
{
    char pool[] = {CHAR_LIST};
    unsigned int pos = 0;
    unsigned int random = 0;
    size_t len = 0;

    len = strlen(pool);

    pw = (char *)malloc(size);
    if (pw == NULL)
        return NULL;

    for (pos = 0; pos < size; pos++)
    {
        random = rand()%len;
        pw[pos] = pool[random];
    }
    return pw;
}

int main(int argc, char **argv)
{
    unsigned int size = 8;
    unsigned int asked = 1;
    int count = 0;

    if (argc != 3)
    {
        printf("PWGen by Atsutane - a simple password generator\n");
        printf("Usage: %s LENGTH COUNT \n", argv[0]);
        return EXIT_SUCCESS;
    }

    srand(time(NULL));
    sscanf(argv[1], "%d", &size);
    sscanf(argv[2], "%d", &asked);

    while (count < asked)
    {
        if (pwgen(size) == NULL)
        {
            return EXIT_FAILURE;
        }

        printf("Password #%d: %s\n",count+1, pw);
        free(pw);
        pw=NULL;

        count++;
    }
    return EXIT_SUCCESS;
}

