﻿
// huffware script: email notecards, by fred huffhines.
//
// this script allows us to export notecards out of the grids.  it reads every notecard
// that's dropped into the object, and then emails it to the specified recipient.
//
// this script is licensed by the GPL v3 which is documented at: http://www.gnu.org/licenses/gpl.html
// do not use it in objects without fully realizing you are implicitly accepting that license.


//hmmm: need a command to clean up the inventory...
//      among things that are not notecards, we need a way to clean up all inventory
//      except the huffotronic updater and this script itself.


// configure these for your own purposes:

// the list of emails that should receive the notecard content.
list EMAIL_LIST_FOR_NOTECARDS = [
    "fred@gruntose.com"
];

// global constants...

integer DEBUGGING = FALSE;  // if true, will make the run a lot noisier.

float TIMER_PERIOD = 2.0;  // period for the timer to check on any pending notecards.

// we'll keep our emails at or under this length.
integer MAXIMUM_STRING_BUFFER = 3200;
  // older versions of opensim have email limit of 1024 for sum of subject and body length.
  // the documented behavior for lsl email is a max of 4096 for sum of subject and body length.

vector TEXT_COLOR = <0.9, 0.7, 0.5>;  // the color the object's text will be painted with.

integer OWNER_ONLY = TRUE;  // if true, only the owner can drop things into the object.

integer PRIVATE_EMAILS = TRUE;  // if true, the names of the recipients are not shown.

// global variables....

key current_query_id = NULL_KEY;  // the query ID for the current notecard.

integer line_number;  // which line are we at in notecard?

string current_notecard_name;  // we are reading a notecard named this, possibly.

list pending_notecards;  // notecards that are going to be read eventually.

integer processing_a_notecard = FALSE;  // are we currently reading and emailing a notecard?

integer need_to_scan_notecards = FALSE;  // should the list of notecards be re-scanned?

/////
//hmmm: add to hufflets...

// basic email sending, with some extra info passed along.
send_email(string recipient, string subject, string content)
{
    if (DEBUGGING) log_it("before sending an email: " + subject);
    llEmail(recipient, subject + " [via " + llKey2Name(llGetOwner()) + "]", content);
    if (DEBUGGING) log_it("after sending an email: " + subject);
}

list __email_buffer;  // contents to send in email should pile up here.

// sends out all the email that's pending in the __email_buffer variable.
send_buffered_email(string subject)
{
    string temp_buffer;  // used to build up the email.
    integer chunk_number = 1;  // tracks which part of the message this is.
    integer i;
    for (i = 0; i < llGetListLength(EMAIL_LIST_FOR_NOTECARDS); i++) {
        string recip = llList2String(EMAIL_LIST_FOR_NOTECARDS, i);
        temp_buffer = "";
        integer j;
        for (j = 0; j < llGetListLength(__email_buffer); j++) {
            string line = llList2String(__email_buffer, j);        
            if (llStringLength(temp_buffer) + llStringLength(line) >= MAXIMUM_STRING_BUFFER) {
                // we're over our limit per email.  send out what we have and
                // then freshen our buffer.
                if (DEBUGGING)
                    log_it("part " + chunk_number + " is " + llStringLength(temp_buffer) + " bytes.");
                send_email(recip, subject + " (part " + chunk_number + ")", temp_buffer);
                temp_buffer = "";
                chunk_number++;
            }
            temp_buffer += llList2String(__email_buffer, j);
        }
        if (llStringLength(temp_buffer) > 0) {
            // send the last piece of the email out.
            if (DEBUGGING)
                log_it("part " + chunk_number + " is " + llStringLength(temp_buffer) + " bytes.");
            send_email(recip, subject + " (part " + chunk_number + ")", temp_buffer);
        }
    }
    __email_buffer = [];  // clear the buffer now that the email is flying out.
}
////// add to hufflets end.
////


// reset any important variables and set up our assets and timers anat.
initialize()
{
    current_query_id = NULL_KEY;
    __email_buffer = [];
    line_number = 0;

    if (OWNER_ONLY) llAllowInventoryDrop(FALSE);  // only owner can drop.
    else llAllowInventoryDrop(TRUE);  // allow people to drop things into us.

    // slap a title on the object.
    string recip_list;
    integer i;
    if (!PRIVATE_EMAILS) {
        for (i = 0; i < llGetListLength(EMAIL_LIST_FOR_NOTECARDS); i++) {
            recip_list += "\n" + llList2String(EMAIL_LIST_FOR_NOTECARDS, i);
        }
    } else recip_list = "private list";
    string prefix;
    if (OWNER_ONLY) prefix = llKey2Name(llGetOwner()) + " can ";
    llSetText(prefix + "drop notecards into me\nto email them to: " + recip_list, TEXT_COLOR, 1.0);
        
    // set the timer to processing notecards that are pending.
    reset_timer(TIMER_PERIOD);
}

//hmmm: add to hufflets?
// safely reschedules the timer for a duration specified.
// this gets around a gnarly SL bug where the timer stops working if not stopped first.
reset_timer(float period)
{
    llSetTimerEvent(0.0);
    llSetTimerEvent(period);
}

// starts reading the current notecard name, which should have been set elsewhere.
consume_notecard()
{
    if (current_notecard_name == "") {
        log_it("somehow we do not have a notecard to read in consume_notecard.");
        return;
    }
    line_number = 0;
    __email_buffer = [];
    current_query_id = llGetNotecardLine(current_notecard_name, 0);    
}

// when the timer goes off, this checks our ongoing processes and kicks them
// down the road a bit if they need it.
handle_timer_pong()
{
    if (processing_a_notecard) return;  // already busy.
    if (need_to_scan_notecards) {
        queue_up_any_new_notecards();
        need_to_scan_notecards = FALSE;
    }

    if (llGetListLength(pending_notecards) < 1) return;  // nothing to do.
    processing_a_notecard = TRUE;
    current_notecard_name = llList2String(pending_notecards, 0);
    if (DEBUGGING) log_it("scheduling notecard: " + current_notecard_name);            
    consume_notecard();
}

// processes the data chunks coming in from our notecard reading.
handle_data_arriving(key query_id, string data)
{
    if (query_id != current_query_id) {
        if (DEBUGGING) log_it("not our query id somehow?");
        return;
    }
    // if we're not at the end of the notecard we're reading...
    if (data != EOF) {
        if (!line_number) {
            if (DEBUGGING) log_it("starting to read notecard " + current_notecard_name + "...");    
        }
        // add the line to our destination list.
        if (is_prefix(data, "From")) data = "#" + data;  // voodoo.
        __email_buffer += [ data + "\n" ];
        if (DEBUGGING) log_it("line " + (string)line_number + ": data=" + data);
        line_number++;  // increase the line count.
        // request the next line from the notecard.
        current_query_id = llGetNotecardLine(current_notecard_name, line_number);
    } else {
        // no more data, so we're done with this card.
        current_query_id = NULL_KEY;
        // blast out the notecard's content in an email.
        llSay(0, "Sending \"" + current_notecard_name + "\" with " + line_number + " lines.\n");
        send_buffered_email(current_notecard_name);
        // chop that name out of our current pending cards too.
        integer where = llListFindList(pending_notecards, [current_notecard_name]);
//log_it("found the notecard to remove at index " + where);        
        if (where >= 0) {
            pending_notecards = llDeleteSubList(pending_notecards, where, where);
        }
        // done with it, so eat the current note card.
        llRemoveInventory(current_notecard_name);
        llSay(0, "Done with notecard \"" + current_notecard_name + "\"; now removing it.");
        // reset our flag to signal that we're ready to eat another notecard.
        processing_a_notecard = FALSE;        
        current_notecard_name = "";
        // make sure we have all current notecards queued.
        need_to_scan_notecards = TRUE;
        // push timer out.
        reset_timer(TIMER_PERIOD);
    }
}

// look through our inventory and if there are any notecards we don't know about,
// add them to the list for processing.
queue_up_any_new_notecards()
{
    integer i;
    for (i = 0; i < llGetInventoryNumber(INVENTORY_NOTECARD); i++) {
        string note_name = llGetInventoryName(INVENTORY_NOTECARD, i);
        // don't add the notecard if the name is already listed.
        integer where = llListFindList(pending_notecards, [ note_name ]);
        if (where >= 0) {
//            if (DEBUGGING) log_it("notecard already present; skipping: " + note_name);
        } else {
            // schedule notecard reading by adding to queue.
            pending_notecards += [ note_name ];
//            if (DEBUGGING) log_it("notecard added to pending: " + note_name);
        }
    }
}

//////////////

// borrowed from hufflets...

integer debug_num = 0;

// a debugging output method.  can be disabled entirely in one place.
log_it(string to_say)
{
    debug_num++;
    // tell this to the owner.    
    llOwnerSay(llGetScriptName() + "[" + (string)debug_num + "] " + to_say);
    // say this on an unusual channel for chat if it's not intended for general public.
//    llSay(108, llGetScriptName() + "[" + (string)debug_num + "] " + to_say);
    // say this on open chat that anyone can hear.  we take off the bling for this one.
//    llSay(0, to_say);
}

//////////////

// the string processing methods are not case sensitive.
  
// returns TRUE if the "pattern" is found in the "full_string".
integer matches_substring(string full_string, string pattern)
{ return (find_substring(full_string, pattern) >= 0); }

// returns the index of the first occurrence of "pattern" inside
// the "full_string".  if it is not found, then a negative number is returned.
integer find_substring(string full_string, string pattern)
{ return llSubStringIndex(llToLower(full_string), llToLower(pattern)); }

// returns TRUE if the "prefix" string is the first part of "compare_with".
integer is_prefix(string compare_with, string prefix)
{ return find_substring(compare_with, prefix) == 0; }

//////////////

//////////////
// huffware script: auto-retire, by fred huffhines, version 2.8.
// distributed under BSD-like license.
//   !!  keep in mind that this code must be *copied* into another
//   !!  script that you wish to add auto-retirement capability to.
// when a script has auto_retire in it, it can be dropped into an
// object and the most recent version of the script will destroy
// all older versions.
//
// the version numbers are embedded into the script names themselves.
// the notation for versions uses a letter 'v', followed by two numbers
// in the form "major.minor".
// major and minor versions are implicitly considered as a floating point
// number that increases with each newer version of the script.  thus,
// "hazmap v0.1" might be the first script in the "hazmap" script continuum,
// and "hazmap v3.2" is a more recent version.
//
// example usage of the auto-retirement script:
//     default {
//         state_entry() {
//            auto_retire();  // make sure newest addition is only version of script.
//        }
//     }
// this script is partly based on the self-upgrading scripts from markov brodsky
// and jippen faddoul.
//////////////
auto_retire() {
    string self = llGetScriptName();  // the name of this script.
    list split = compute_basename_and_version(self);
    if (llGetListLength(split) != 2) return;  // nothing to do for this script.
    string basename = llList2String(split, 0);  // script name with no version attached.
    string version_string = llList2String(split, 1);  // the version found.
    integer posn;
    // find any scripts that match the basename.  they are variants of this script.
    for (posn = llGetInventoryNumber(INVENTORY_SCRIPT) - 1; posn >= 0; posn--) {
        string curr_script = llGetInventoryName(INVENTORY_SCRIPT, posn);
        if ( (curr_script != self) && (llSubStringIndex(curr_script, basename) == 0) ) {
            // found a basic match at least.
            list inv_split = compute_basename_and_version(curr_script);
            if (llGetListLength(inv_split) == 2) {
                // see if this script is more ancient.
                string inv_version_string = llList2String(inv_split, 1);  // the version found.
                // must make sure that the retiring script is completely the identical basename;
                // just matching in the front doesn't make it a relative.
                if ( (llList2String(inv_split, 0) == basename)
                    && ((float)inv_version_string < (float)version_string) ) {
                    // remove script with same name from inventory that has inferior version.
                    llRemoveInventory(curr_script);
                }
            }
        }
    }
}
//
// separates the base script name and version number.  used by auto_retire.
list compute_basename_and_version(string to_chop_up)
{
    // minimum script name is 2 characters plus a version.
    integer space_v_posn;
    // find the last useful space and 'v' combo.
    for (space_v_posn = llStringLength(to_chop_up) - 3;
        (space_v_posn >= 2) && (llGetSubString(to_chop_up, space_v_posn, space_v_posn + 1) != " v");
        space_v_posn--) {
        // look for space and v but do nothing else.
    }
    if (space_v_posn < 2) return [];  // no space found.
    // now we zoom through the stuff after our beloved v character and find any evil
    // space characters, which are most likely from SL having found a duplicate item
    // name and not so helpfully renamed it for us.
    integer indy;
    for (indy = llStringLength(to_chop_up) - 1; indy > space_v_posn; indy--) {
        if (llGetSubString(to_chop_up, indy, indy) == " ") {
            // found one; zap it.  since we're going backwards we don't need to
            // adjust the loop at all.
            to_chop_up = llDeleteSubString(to_chop_up, indy, indy);
        }
    }
    string full_suffix = llGetSubString(to_chop_up, space_v_posn, -1);
    // ditch the space character for our numerical check.
    string chop_suffix = llGetSubString(full_suffix, 1, llStringLength(full_suffix) - 1);
    // strip out a 'v' if there is one.
    if (llGetSubString(chop_suffix, 0, 0) == "v")
        chop_suffix = llGetSubString(chop_suffix, 1, llStringLength(chop_suffix) - 1);
    // if valid floating point number and greater than zero, that works for our version.
    string basename = to_chop_up;  // script name with no version attached.
    if ((float)chop_suffix > 0.0) {
        // this is a big success right here.
        basename = llGetSubString(to_chop_up, 0, -llStringLength(full_suffix) - 1);
        return [ basename, chop_suffix ];
    }
    // seems like we found nothing useful.
    return [];
}
//
//////////////

// end from hufflets.
//////////////

default {
    state_entry() { if (llSubStringIndex(llGetObjectName(), "huffotronic") < 0) state real_default; }
    on_rez(integer parm) { state rerun; }
}
state rerun { state_entry() { state default; } }

state real_default
{
    state_entry() {
        auto_retire();
        initialize();
    }
    
    changed(integer mask) {
        if (mask & (CHANGED_ALLOWED_DROP | CHANGED_INVENTORY)) {
            need_to_scan_notecards = TRUE;
            pending_notecards = [];  // reset the list so we re-add all and drop any dead ones.
            reset_timer(TIMER_PERIOD);
        }
    }
    
    timer() { handle_timer_pong(); }
    
    dataserver(key query_id, string data) { handle_data_arriving(query_id, data); }        
}
