#include "shared_testpilot_util.h"

void get_tpass(char *basename, int rotate, char *password)
{
    char base[37] = "ab0c5de2fgh1ijk3lmn6opq7rst9uv8wx4yz";
    int i, j, n =0;
    int bNlen = strlen(basename);
    int blen = strlen(base);
    rotate = rotate -1;

    for (i =0; i<bNlen; i++)
    {
       for(j =0; j<strlen(base); j++)
       {
         if(basename[i] == base[j])
	 {
	       if( (j + rotate) < blen)
	       {
		  password[n] = base[j+rotate];
		  password[n+1] = '\0'; 
	       }
	       else
	       {
		  password[n] = base[j+rotate - blen];
		  password[n+1] = '\0'; 
	       }
	       n++;
	 }
       }	       
    }   
}


void makeTestPassword(char *username, char *crs, char *newPassword)
{
    char basename[MAX_PATH +1];
    int len =0;
    int rotate = 0;
    int num =0;
    char temp[10];

    snprintf(basename, MAX_PATH +1, "%s%s", crs, username);
    len = strlen(basename);
    if(isdigit(basename[len -1]))
    {
        snprintf(temp, 10, "%c", basename[len -1]);
	num = atoi(temp);
	if(num % 2 == 0)
             rotate = 13;
	else 
	    rotate = 17;
    }
    else
	rotate = 15; 

    get_tpass(basename, rotate, newPassword);
     
}

void get_testpilot_admin_pass(char *path, char *username, char *pass)
{
   char line[MAX_PATH +1];
   char *ptr;

   FILE *fp;
   fp = fopen(path, "r");
   if(!fp)
	 cs_critical_error(ERR_FREAD_FAILED, "news_topic get_test_pilot_password");
   fgets(line, MAX_PATH +1, fp);
   fclose(fp);

   ptr = strchr(line, '/');
   if(ptr)
   {
   *ptr = '\0';

   cs_set_value("admin_name", line);
   snprintf(username, MAX_USERNAME +1, "%s", line);
   ptr++;
   cs_set_value("admin_pass", ptr);
   snprintf(pass, MAX_PASSWORD +1, "%s", ptr);
  }
  else
  {
	*username = '\0';
	*pass = '\0';
  }
}


int get_test_pilot_password(SESSION *user, char *passwd)
{
    char path[MAX_PATH +1];
    FILE *fp;

    snprintf(path, MAX_PATH +1, "../%s/%c/%s/%s", USERS_DIR, sub_dir_name(user->username), user->username, TESTPILOT_FNAME);
    if(!file_exists(path))
    {
        cs_set_int_value("TESTPILOT_ACCOUNT", 0);
        return 0; 
    }
    fp = fopen(path, "r");
    if(!fp)
	 cs_critical_error(ERR_FREAD_FAILED, "news_topic get_test_pilot_password");
    fgets(path, MAX_PATH +1, fp);
    strtrm(path); 
    cs_set_int_value("TESTPILOT_ACCOUNT", 1);
    cs_set_value("TESTPILOT_PASSWORD", path);
    fclose(fp); 
    snprintf(passwd, MAX_PATH +1, "%s", path);
    return 1;   
}


void get_testpilot_view_record_path(const char *course_path, const char *username, const char *sender, const char *info_fname,
				char *path)
{
 snprintf(path,MAX_PATH + 1, "%s%s/%s/%s/%s_%s%s",course_path, PEOPLE_DIR, username,
                                                       TESTPILOT_DIR,sender,info_fname, TESTPILOT_VIEW_EXTENSION);
}
