/*
	Auther	Satoshi Yasuda	7m3tjz/ad6gz

	password file /etc/ds_passwd

*/

#define         _XOPEN_SOURCE

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

void main(int argc, char *argv[])
{
	FILE	*pwd_file;
	char	buf[256];
	char	pass1[128];
	char	pass2[128];
	char	salt[8];
	char	key[13];
	char	*call;
	unsigned int	k;
	int	i;

	if (argc != 2)
	{
		printf ("usage: ds_adduser Callsign\n");
		exit (0);
	}

	call = argv[1];
	
	for (i = 0 ; i < strlen(argv[1]) ; i++)
	{
		*call = toupper(*call); 
		call++;
	}

	pwd_file = fopen ("/etc/ds_passwd", "r");

	while (fgets (buf, 255, pwd_file))
	{
		for (i = 0 ; i < strlen(buf) ; i++)
		{
			if (buf[i] == ':')
			{
				buf[i] = 0x00;
				break;
			}
		}
		if (strcmp(buf, argv[1]) == 0)
		{
			printf ("Already exist %s\n", argv[1]);
			fclose (pwd_file);
			exit(0);
		}
	}
	fclose (pwd_file);
	
        srand ((unsigned) time (NULL)); 

	system ("stty -echo");
	
	printf ("Passwword:");
	fgets (pass1, 127, stdin);
	printf ("\nRetype Password:");
	fgets (pass2, 127, stdin);

	if ((strlen(pass1) <= 1) && (strlen(pass2) <= 1))
	{
		system ("stty echo");
		printf ("\n");
		exit(0);
	} 
	while (strcmp (pass1, pass2))
	{
		printf ("\nSorry, Password does not match.\n");
		printf ("Password:");
		fgets (pass1, 127, stdin);
		printf ("\nRetype Password:");
		fgets (pass2,127, stdin);
		if ((strlen(pass1) <= 1) && (strlen(pass2) <= 1))
		{
			system ("stty echo");
			printf ("\n");
			exit(0);
		}
	}
 
	system("stty echo");
	printf ("\n");

	pass1[strlen(pass1) - 1] = 0x00;
	
	for (i = 0 ; i < 8 ;i++)
	{
		k = rand() % 64;
		if (k < 10) salt[i] = k + '0';
		else if (k < 36) salt[i] = k + 'A' - 10;
		else if (k < 62) salt[i] = k +'a' - 36;
		else if (k == 62) salt[i] = '.';
		else if (k == 63) salt[i] = '/';
	}
	key[12] = 0x00;
	
	pwd_file = fopen ("/etc/ds_passwd", "a");
		
	sprintf (key,"$6$%8.8s$",salt);

	fprintf (pwd_file, "%s:%s:\n",argv[1], crypt(pass1,key));

	fclose (pwd_file);

}

