/* Copying and distribution of this file, with or without modification,
 * are permitted in any medium without royalty provided the copyright
 * notice and this notice are preserved.  This file is offered as-is,
 * without any warranty.
 */

import std;
import amalthea.fs;

auto sortEntries(Range)(Range r) {
    return sort!"a.path < b.path"(r).array;
}

void main(string[] args) {
    bool hidden;
    bool recursively;
    bool symlinksOnly, regularFilesOnly, directoriesOnly;
    getopt(args, "hidden",      &hidden,
                 "recurse",     &recursively,
                 "symlinks",    &symlinksOnly,
                 "files",       &regularFilesOnly,
                 "directories", &directoriesOnly);
    auto hFlag = hidden ? Yes.hidden : No.hidden;
    auto rFlag = recursively ? Yes.recursively : No.recursively;

    string dir = args.length > 1 ? args[1] : ".";

    FileEntry[] files;
    if (directoriesOnly) {
        files = amalthea.fs.getDirectories(dir, hFlag, rFlag);
    } else if (regularFilesOnly) {
        files = amalthea.fs.getRegularFiles(dir, hFlag, rFlag);
    } else if (symlinksOnly) {
        files = amalthea.fs.getSymlinks(dir, hFlag, rFlag);
    } else {
        files = amalthea.fs.getFiles(dir, hFlag, rFlag);
    }
    files = sortEntries(files).array;

    foreach(f; files) {
        auto st = f.getFileStat();
        makeUnixFileModeLine(st).write;
        write(" ");
        std.path.baseName(f.path).writeln;
    }
}
