#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
#include <string.h>
#include <iostream>

using namespace std;

string header1="<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\"><title>My All File List</title>";
string header2="<meta name=\"GENERATOR\" content=\"Microsoft FrontPage 6.0\"></head>  <body><p><font color=\"#FF0000\">";
string header3="<font color=\"#FF0000\"><font size=\"7\">All File List</font></p>";

string tableHeader1="<table border=\"1\" cellpadding=\"5\" cellspacing=\"5\" width=\"100%\">";
string tableHeader2="<tr> <th> file index </th>  <th> file name </th>   </tr>";
string bottom="</table></body></html>";

string tableColumn1 = "<tr> <td width=20>";
string tableColumn2 = "</td>  <td> <a href=\"http://www.staroceans.org.s3-website-us-east-1.amazonaws.com/";
string tableColumn3 = "\">";
string tableColumn4 = "</a> </td> </tr>";
int rootLength = 0;
int total = 0;

bool dirfilter(char* name)
{
    return strcmp(name, "personal") != 0;
}

bool filefilter(char* name)
{
    return strcmp(name, "unPublished.htm") != 0;
}


void foreachDir(string dir)
{
    DIR *dp;
    struct dirent *dirp;
    struct stat stDirInfo;
    size_t subLength = dir.length();
    string subDir;

    if (lstat( dir.c_str(), &stDirInfo) == 0)
    {
        if (S_ISDIR(stDirInfo.st_mode))
        {
            if (dirfilter(dirp->d_name))
            {
                if ((dp  = opendir(dir.c_str())) != NULL)
                {
                    while ((dirp = readdir(dp)) != NULL)
                    {
                        //files.push_back(string(dirp->d_name));
                        if (strcmp(dirp->d_name, ".") != 0 && strcmp(dirp->d_name, "..") != 0)
                        {
                            subDir = dir + string("/") + string(dirp->d_name);
                            if (filefilter(dirp->d_name))
                            {
                                foreachDir(subDir);
                            }
                        }
                    }
                    closedir(dp);
                }
            }
        }
        else
        {
            if (S_ISREG(stDirInfo.st_mode))
            {
                subDir = dir.substr(rootLength, subLength - rootLength);
                //cout<<"file:"<<dir<<"subDir"<<subDir<<endl;
                total++;
                cout <<tableColumn1<<total<<tableColumn2<<subDir<<tableColumn3<<subDir<<tableColumn4<<endl;

            }
        }
    }

}


int main(int argc, char**argv)
{
    int total = 0;
    if (argc == 2)
    {
        string dir = string(argv[1]);
        rootLength = dir.length() + 1;

        cout<<header1<<header2<<header3<<endl;
	    cout<<tableHeader1<<tableHeader2<<endl;

        foreachDir(dir);
        //cout << "total = "<< total<<endl;

	    cout<< bottom<<endl;
    }
    return 0;
}
