#! /usr/bin/env node

// Get logs for the a device running the current model

var program = require("commander");
var prompt = require("cli-prompt");
var colors = require("colors");
var fs = require("fs");

var ImpConfig = require("../lib/impConfig.js");
var config = new ImpConfig();

var messageFormat = {
    "agent.log":    { message: "[Agent]", color: colors.cyan },
    "agent.error":  { message: "[Agent]", color: colors.red },
    "server.log":   { message: "[Device]", color: colors.blue },
    "server.error": { message: "[Device]", color: colors.red },
    "server.sleep": { message: "[Device]", color: colors.blue },
    "powerstate":   { message: "[Device]", color: colors.blue },
    "lastexitcode": { message: "[Device]", color: colors.blue },
    "firmware":     { message: "[Device]", color: colors.blue },
    "status":       { message: "[Status]", color: colors.yellow }
};

program
    .option("-d, --device <deviceID>", "The device ID you would like to see logs for")
    .option("-t, --title <deviceName>", "The device name you would like to see logs for")
// Note: can't use 'name' as an option - it's reserved

program.parse(process.argv);

if (!("device" in program || "title" in program)) {
    // log requires a device name or ID
    console.log("ERROR: You must specify a device with '-d <deviceID>' or '-t <deviceName>'");
    return;
}

function formatDate(d) {
    var pad = function(num, size) {
        if (!size) size = 2;
        var s = "000000000" + num;
        return s.substr(s.length-size);
    };

    return d.getFullYear() + "-" + pad(d.getMonth() + 1) + "-" + pad(d.getDay()) + " "
        + pad(d.getHours()) + ":" + pad(d.getMinutes()) + ":" + pad(d.getSeconds()) + " "
        + "UTC" + (d.getTimezoneOffset() / -60)
}

function formatMessage(log) {
    var format = messageFormat[log.type];
    return colors.grey(formatDate(new Date(log.timestamp))) + " "
         + format.color(format.message) + "\t"
         + colors.grey(log.message);
}

function startLog(deviceID) {
    imp.streamDeviceLogs(deviceID, function(err, data) {
        if (err) {
            console.log("ERROR: " + err.message_short);
            return;
        }

        if ("logs" in data) {
            data.logs.forEach(function(log) {
                console.log(formatMessage(log));
            });
        }
    });
}

config.init(["apiKey"], function(err, success) {
    if (err) {
        console.log("ERROR: Global Build API key is not set - run 'imp setup' then try 'imp log' again");
        return;
    }

    imp = config.createImpWithConfig();

    if ("title" in program) {
        // Convert passed in device name to a device ID
        var devId = null;
        imp.getDevices(null, function(err, data) {
            if (err) {
                console.log("ERROR: " + err.message_short);
                return;
            }

            data.devices.forEach(function(device) {
                if (device.name == program.title) devId = device.id;
            });

            if (devId) {
                console.log("Opening stream for device '" + program.title + "'. Hit Ctrl-C to quit logging");
                startLog(devId);
            } else {
                console.log("ERROR: There is no device of name '" + program.title + "'");
            }
        });
    } else {
        console.log("Opening stream for device '" + program.device + "'. Hit Ctrl-C to quit logging");
        startLog(program.device);
    }
});

@@ -1072,16 +1072,99 @@
 s for%22)%0A
+    .option(%22-l, --list%22, %22Present the most recent logs rather than a stream%22)%0A    
 // Note:
@@ -1330,16 +1330,25 @@
 name or 
+a device 
 ID%0A    c
@@ -2091,24 +2091,30 @@
 ion startLog
+Stream
 (deviceID) %7B
@@ -2439,16 +2439,373 @@
  %7D);%0A%7D%0A%0A
+function getLogs(deviceID) %7B%0A    imp.getDeviceLogs(deviceID, null, function(err, data) %7B%0A        if (err) %7B%0A            console.log(%22ERROR: %22 + err.message_short);%0A            return;%0A        %7D%0A%0A        if (%22logs%22 in data) %7B%0A            data.logs.forEach(function(log) %7B%0A                console.log(formatMessage(log));%0A            %7D);%0A        %7D%0A    %7D);%0A%7D%0A%0A
 config.i
@@ -3028,16 +3028,38 @@
 onfig();
+%0A    var devId = null;
 %0A%0A    if
@@ -3141,34 +3141,31 @@
 e ID
-%0A        var devId = null;
+ and then start logging
 %0A   
@@ -3488,16 +3488,17 @@
     if (
+!
 devId) %7B
@@ -3502,172 +3502,8 @@
 ) %7B%0A
-                console.log(%22Opening stream for device '%22 + program.title + %22'. Hit Ctrl-C to quit logging%22);%0A                startLog(devId);%0A            %7D else %7B%0A
     
@@ -3584,24 +3584,48 @@
 tle + %22'%22);%0A
+                return;%0A
             
@@ -3649,18 +3649,290 @@
  %7D else 
-%7B%0A
+if (%22device%22 in program) %7B%0A        // Just use the passed in ID; we'll check for a valid ID later%0A        devId = program.device;%0A    %7D%0A%0A    if (%22list%22 in program) %7B%0A        // User wants a log dump%0A        getLogs(devId);%0A    %7D else %7B%0A        if (%22title%22 in program) %7B%0A    
         
@@ -3983,21 +3983,20 @@
 program.
-devic
+titl
 e + %22'. 
@@ -4037,31 +4037,163 @@
     
-startLog(program.device
+%7D else %7B%0A            console.log(%22Opening stream for device '%22 + program.device + %22'. Hit Ctrl-C to quit logging%22);%0A        %7D%0A%0A        startLogStream(devId
 );%0A 

Update imp-log.js