#!/usr/bin/env perl

use Mojolicious::Lite;
use Data::Dump qw(dump);

# Documentation browser under "/perldoc" (this plugin requires Perl 5.10)
plugin 'pod_renderer';

helper get_files => sub {
	my $self = shift;
warn "XXXXX ", dump( $self->req->url->path->to_string );

	my $path = $self->req->url->path->to_string;
	$path =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/ge; # url_unescape;
	$path =~ s{^.*~/}{};

 	$self->stash( full_path => $path );

	return $self->redirect_to( $path ) if -f $path;

	my $files = [
		map {
			$_ .= '/' if -d $_;
			s{$path/}{};
			$_;
		}
		glob "$path/*"
	];

	warn "# path $path ",dump($files);

	$self->stash( files => $files );
};

get '/~/*path' => sub {
	my $self = shift;
	warn "no path";
	$self->get_files;

	if ( -f $self->stash('full_path') ) {
		return $self->redirect_to( $self->stash( 'full_path' ) );
	}

	$self->render('user');
};

get '/' => sub {
	my $self = shift;
	$self->render('index');
};

get '/_admin/users' => sub {
	my $self = shift;

	my @users =
		map { s{/secrets}{}; $_ }
		glob   'users/*/secrets';

	$self->render('users', users => \@users );
};

app->start;
__DATA__

@@ layouts/default.html.ep
<!doctype html><html>
  <head><title><%= title %></title></head>
  <body>
<%= content %>
  </body>
</html>


@@ index.html.ep
% layout 'default';

<%= link_to 'list users' => '_adminusers' %>


@@ users.html.ep
% layout 'default';
% title 'Welcome to CloudShare';

<h1>Users</h1>
<ul>
% foreach my $login ( @$users ) {
<li><a href="/~/<%= $login %>/"><%= $login %></a>
% }
</ul>


@@ user.html.ep
% layout 'default';

<h1><%= $full_path %></h1>

<ul>
% foreach my $path ( @$files ) {
<li><a href="<%= $path %>"><%= $path %></a>
% }
</ul>

