#!/usr/bin/perl
# Readline-autocomplete for tw_cli
# Copyright 2009-2010
# Allen Parker <infowolfe@isohunt.com>
# Robin H. Johnson <robbat2@isohunt.com>
# GPL-2
use Term::ReadLine;
use strict;
use warnings;

my $model = '';
$model = `tw_cli show | grep ^c.* | awk {'print \$2'}`;
chomp $model;


my $term = new Term::ReadLine '3ware readline cli';
my $attribs = $term->Attribs;
our $prompt;
my $OUT = $term->OUT || 'STDOUT';

&prompt;

$attribs->{completion_function} = sub {
	my ($text, $line, $start) = @_;
	# TODO: finish me
	return qw();
};

my $path = '';
while ( defined ($_ = $term->readline($prompt)) ) {
	chomp $_;
	if (/^(up|cd)$/) {
		$path = '';
		&prompt;
	} elsif ($_ eq '') {
		print "you need to enter a command, try 'help'\n";
	} elsif (/cd.*/i) {
		s/cd //;
		if ( /^\/.*/ ) {
			$path = $_;
			&prompt
		} elsif (/^\.\.$/) {
			my @split = split "\/", $path;
			my $fail = pop(@split);
			my $newpath = join "\/", @split;
			$path = $newpath;
			&prompt
		} elsif (! /^\/.*/) {
			$path = $path."/".$_;
			&prompt
		} else {
			$path = $path.$_;
			&prompt
		}
	} elsif (/^(ls|cards)$/) {
		my $cmd = `tw_cli show`;
		print $cmd;
	} elsif (/^(exit|quit)$/) {
		print "thanks for playing tw_cli!\n";
		exit;
	} else {
		my $cmd = `tw_cli $path $_`;
		print $cmd;
	}

#	$res = `tw_cli $_`;
#	warn $@ if $@;
#	print $OUT $res, "\n" unless $@;
#	$term->addhistory($_) if /\S/;
}

sub prompt {
	$prompt = sprintf("%s@%s> ", $model, $path);
}
