/*
	Parse "ls -l --full-time" output.
	Produce simplified machine readable format.
*/

%{
#include <string.h>
#include <time.h>

char dir[500]="", perm[20], *basedir = 0;
int size, month, day, year, hour, minute, second, is_link, is_dir;

int month_number(char *m)
{
  if (!strcmp(m,"Jan")) return 0;
  else if (!strcmp(m,"Feb")) return 1;
  else if (!strcmp(m,"Mar")) return 2;
  else if (!strcmp(m,"Apr")) return 3;
  else if (!strcmp(m,"May")) return 4;
  else if (!strcmp(m,"Jun")) return 5;
  else if (!strcmp(m,"Jul")) return 6;
  else if (!strcmp(m,"Aug")) return 7;
  else if (!strcmp(m,"Sep")) return 8;
  else if (!strcmp(m,"Oct")) return 9;
  else if (!strcmp(m,"Nov")) return 10;
  else if (!strcmp(m,"Dec")) return 11;
}

int yywrap() { return feof(stdin); }

int main() 
{ 
  yylex(); 
  return 0; 
}

%}

DIGIT    [0-9]
ALPHA    [A-Za-z]
DIRBIT   [dl\-]
PERMGROUP [r\-][w\-][x\-]
PERMFIELD {DIRBIT}{PERMGROUP}{3}
MONTH    Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec
TIME     {DIGIT}{2}:{DIGIT}{2}
NUMBER   {DIGIT}+
WS       [ \t]+

%s SIZE
%s DOW
%s MONTH
%s DAY
%s TIME
%s YEAR
%s FILENAME
%s LINKNAME

%%

^"total "[0-9]+"\n" ;

^[dl\-]([r\-][w\-][x\-]){3}[ \t]+ {
  strcpy(perm,yytext); 
  is_link = (perm[0] == 'l');
  is_dir = (perm[0] == 'd');
  BEGIN(SIZE); 
}

^.*/":\n" {
  strcpy(dir,yytext);
  basedir = dir;
//  if (!basedir)
//    basedir = strrchr(dir,'/')+1;
}

":\n" |
"\n" BEGIN(INITIAL);

<SIZE>[0-9]+[ \t]+ {
  size = atoi(yytext); 
}

<SIZE>. ;

<SIZE>(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[ \t]+ {
/*
  yytext[3] = 0;
  month = month_number(yytext);
*/
  BEGIN(MONTH);
}

<MONTH>(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[ \t]+ {
  yytext[3] = 0;
  month = month_number(yytext);
  BEGIN(DAY);
}

<DAY>[0-9]+[ \t]+ {
  day = atoi(yytext);
  BEGIN(TIME);
}

<TIME>[0-9][0-9]":"[0-9][0-9]":"[0-9][0-9][ \t]+ {
  hour = atoi(yytext);
  minute = atoi(yytext+3);
  second = atoi(yytext+6);
  BEGIN(YEAR);
}

<YEAR>[0-9]+[ \t]+ {
  year = atoi(yytext);
  BEGIN(FILENAME);
}

<FILENAME>.*"\n" {
  char *end = yytext + strlen(yytext) - 1;
  switch (*(end-1)) {
    case '/':
    case '*':
    case '@': end--;
  }
  *end = 0;  // remove optional '/' and '\n'
  if (is_link) {
    char *extra = strstr(yytext, " -> ");
    if (extra)
      *extra = 0;
  }
  if (basedir)
    printf("%s ", basedir);
  else
    printf(". ");
  printf("%s %04d%02d%02d%02d%02d%02d ",yytext,year,month,day,hour,minute,second);
  if (is_link) {
    printf("link");
  } else if (is_dir) printf("dir");
  else printf("%d", size);
  printf("\n");
  BEGIN(INITIAL);
}

%%


