//############################################################################################################
//# Reference : 
//#  ZFSSA Scripting       - http://docs.oracle.com/cd/E27998_01/html/E48433/user_interface__cli__scripting.html#scrolltoc
//#  ZFSSA Analytics Guide - http://docs.oracle.com/cd/E27998_01/html/E48490/index.html
//#  ECMA Script Doc       -  http://www.ecmascript.org/docs.php
//#  ECMA Script Reference -  http://qt-project.org/doc/qt-4.8/ecmascript.html
//#  ECMA Script Reference -  http://qt-project.org/doc/qt-4.8/ecmascript.html
//#############################################################################################################


//#######################################
//# ZFS Storage Appliance Scriptlets 
//#######################################


 //this is a single-line comment
 /* this is a multiline
      comment */

//##################
//# Sample Run
//##################
ssh -T ipaddress  < inputscript.txt > output.txt

or
ssh -T ipaddress  <<EOF
...
...
EOF

//#######################################
//# Custom Function Library
//#######################################
script
  function BytesToString(bytes)
  {
        if      (bytes>=Math.pow(1024,5)) {bytes=(bytes/Math.pow(1024,5)).toFixed(2)+'PB';}
        else if (bytes>=Math.pow(1024,4)) {bytes=(bytes/Math.pow(1024,4)).toFixed(2)+'TB';}
        else if (bytes>=Math.pow(1024,3)) {bytes=(bytes/Math.pow(1024,3)).toFixed(2)+'GB';}
        else if (bytes>=Math.pow(1024,2)) {bytes=(bytes/Math.pow(1024,2)).toFixed(2)+'MB';}
        else if (bytes>=Math.pow(1024,1)) {bytes=(bytes/Math.pow(1024,1)).toFixed(2)+'KB';}
        else if (bytes>1)           {bytes=bytes+' bytes';}
        else if (bytes==1)          {bytes=bytes+' byte';}
        else                        {bytes='0 byte';}
        return bytes;
  }

  function SuffixToMultiplier(suffix)
  {
     switch (suffix)
     {
       case('K'): return  Math.pow(1024,1); break;
       case('M'): return  Math.pow(1024,2); break;
       case('G'): return  Math.pow(1024,3); break;
       case('T'): return  Math.pow(1024,4); break;
       case('P'): return  Math.pow(1024,5); break;
       default:   return  1; break;
     }
 }

  function lpad(str, len, pad) {
      if (typeof(len) == "undefined") { var len = 0; }
      if (typeof(pad) == "undefined") { var pad = ' '; }
      if (len + 1 >= str.length) {
          str = Array(len + 1 - str.length).join(pad) + str;
      }
      return str;
  }
  function rpad(str, len, pad) {
      if (typeof(len) == "undefined") { var len = 0; }
      if (typeof(pad) == "undefined") { var pad = ' '; }
      if (len + 1 >= str.length) {
          str = str + Array(len + 1 - str.length).join(pad);
      }
      return str;
  }

  function pad(str, len, pad, dir) {
      if (typeof(len) == "undefined") { var len = 0; }
      if (typeof(pad) == "undefined") { var pad = ' '; }
      if (typeof(dir) == "undefined") { var dir = STR_PAD_RIGHT; }
      if (len + 1 >= str.length) {
          switch (dir){
              case STR_PAD_LEFT: str = Array(len + 1 - str.length).join(pad) + str; break;
              case STR_PAD_BOTH:
                  var right = Math.ceil((padlen = len - str.length) / 2);
                  var left = padlen - right;
                  str = Array(left+1).join(pad) + str + Array(right+1).join(pad);
                  break;
              default: str = str + Array(len + 1 - str.length).join(pad);
                       break;

          } // switch
      }
      return str;
  }
 
.




//#######################################
//# Dashboard View
//#######################################
cd /
status dashboard 

//#######################################
//# Show Status
//#######################################
cd / 
status storage show
status memory show
status hardware show
status alerts show
status services show

//#######################################
//# Show Resilver progress
//#######################################
cd / 
configuration storage get scrub


//#######################################
//# Show Configuration
//#######################################
cd /
configuration version show
configuration storage show
configuration cluster show
configuration cluster resources show
script
   run('cd /');
   var ZFSSA_NODENAME =  run('configuration version get nodename').split(/\s+/)[3]
   run('configuration net datalinks');
   datalinks = list();
   var    FORMAT='%-10s %-8s %-15s %-20s %-20s %-20s %-5s %-6s %-9s %-5s %-5s %-5s %-5s %-5s %-8s \n';
   printf(FORMAT,'ZFSSANode','Datalink','Class','Label','MAC','Links','MTU','policy','Mode','Timer','Key','Speed','Duplex','pkey','linkmode');
   printf(FORMAT,'=========','========','=====','=====','===','=====','===','======','====','=====','===','=====','======','====','========')';
   for (i = 0; i < datalinks.length; i++)
   {
      run('select ' + datalinks[i]);
      var class  = run('get class').split(/=/)[1].split(/\n/)[0].substr(1) ;
      var label  = run('get label').split(/=/)[1].split(/\n/)[0].substr(1) ;
      var mac    = run('get mac').split(/=/)[1].split(/\n/)[0].substr(1)   ;
      var links  = run('get links').split(/=/)[1].split(/\n/)[0].substr(1) ;
      var mtu    = run('get mtu').split(/=/)[1].split(/\n/)[0].substr(1)   ;
      var policy = '';
      var mode = '';
      var timer = '';
      var key = '';
      var speed = '';
      var duplex = '';
      var pkey = '';
      var linkmode = '';
      if class = 'aggregation'
      {
         policy = run('get policy').split(/=/)[1].split(/\n/)[0].substr(1);
         mode    = run('get mode').split(/=/)[1].split(/\n/)[0].substr(1)   ;
         timer  = run('get timer').split(/=/)[1].split(/\n/)[0].substr(1);
         key    = run('get key').split(/=/)[1].split(/\n/)[0].substr(1);
      }
      if class = 'device'
      {
         speed  = run('get speed').split(/=/)[1].split(/\n/)[0].substr(1) ;
         duplex = run('get duplex').split(/=/)[1].split(/\n/)[0].substr(1) ;    
      }
      if class = 'partition'
      {
         pkey     = run('get pkey').split(/=/)[1].split(/\n/)[0].substr(1)      ;
         linkmode = run('get linkmode').split(/=/)[1].split(/\n/)[0].substr(1)  ; 
      }
      printf(FORMAT, ZFSSA_NODENAME, datalinks[i], class, label, mac, links,mtu,policy,mode,timer,key,speed,duplex,pkey,linkmode);
      run('cd ..');
   }
.
configuration net datalinks show
configuration net devices show
configuration net interfaces show
configuration net routing show


//#######################################
//# Show Configuration
//#######################################
cd /
configuration version show
configuration storage show
configuration cluster show
configuration cluster resources show

script
   var timestampformat='%Y-%m-%d %H:%M:%S (%Z)';
   run('cd /');
   var ZFSSA_NODENAME =  run('configuration version get nodename').split(/\s+/)[3]
   run('configuration net datalinks');
   datalinks = list();
   var    FORMAT='%-10s %-8s %-15s %-20s %-20s %-20s %-5s %-6s %-9s %-5s %-5s %-5s %-5s %-5s %-8s \n';
   printf(FORMAT,'ZFSSANode','Datalink','Class','Label','MAC','Links','MTU','policy','Mode','Timer','Key','Speed','Duplex','pkey','linkmode');
   printf(FORMAT,'=========','========','=====','=====','===','=====','===','======','====','=====','===','=====','======','====','========');
   for (i = 0; i < datalinks.length; i++)
   {
      run('select ' + datalinks[i]);
      class  = get('class');
      label  = get('label');
      mac    = get('mac');
      links  = get('links');
      mtu = '';
      policy = '';
      mode = '';
      timer = '';
      pkey = '';
      speed = '';
      duplex = '';
      pkey = '';
      linkmode = '';
      if ( class == 'aggregation' )
      {
         mtu    = get('mtu');
         policy = get('policy') ;
         mode   = get('mode')   ;
         timer  = get('timer')  ;
         key    = get('key')    ;
      }
      if ( class == 'device' )
      {
         mtu    = get('mtu');
         speed  = get('speed') ;
         duplex = get('duplex') ;    
      }
      if ( class == 'partition' )
      {
         pkey     = get('pkey')      ;
         linkmode = get('linkmode')  ; 
      }
      printf(FORMAT
           , ZFSSA_NODENAME
           , datalinks[i]
           , class
           , label
           , mac
           , links
           , mtu
           , policy
           , mode
           , timer
           , key
           , speed
           , duplex
           , pkey
           , linkmode
           );
           run('cd ..');
   }
.

configuration net datalinks show
configuration net devices show
configuration net interfaces show
configuration net routing show


//#######################################
//# Show Alerts
//#######################################
script
  var timestampformat='%Y-%m-%d %H:%M:%S (%Z)';
  run('cd /');
  var ZFSSA_NODENAME =  run('configuration version get nodename').split(/\s+/)[3]
  run('maintenance logs select alert');
  alerts = list();
  var FORMAT='%-10s %-12s %-26s %-100s\n';
  printf(FORMAT,'ZFSSA Node','Type'        ,'Time'                     , 'Description');
  printf(FORMAT,'==========','===========' ,'=========================' ,'=====================');
  for (i = 0; i < alerts.length; i++) 
  {
      run('select ' + alerts[i]);
      var type = get('type');
      var timestamp = get('timestamp').toLocaleFormat(timestampformat).toUpperCase();
      var description = get('description');
      var type_searchstring = '.*'
      /* var timestamp_searchstring = '2014-6-1[1,2]' */
      var timestamp_searchstring = '.*'
      var description_searchstring = '.*';
      if ( description.search( description_searchstring ) > -1 
           && timestamp.search(timestamp_searchstring) > -1 
           &&  type.search( type_searchstring ) > -1 
         )
      {
        printf(FORMAT
             , ZFSSA_NODENAME
             , type
             , timestamp
             , description
             );
      }       
      run('cd ..');
  }
.



//#######################################
//# Show NDMP Backups
//#######################################
script
  var timestampformat='%Y-%m-%d %H:%M:%S (%Z)';
  print('############################################################' );
  print('NDMP Backups [' + new Date() + ']\n')
  print('############################################################' );
  run('cd /');
  var ZFSSA_NODENAME =  run('configuration version get nodename').split(/\s+/)[3]
  run('maintenance logs select alert');
  alerts = list();
  var FORMAT='%-10s %-20s %-15s %-25s %-25s %-20s\n';
  printf(FORMAT,'ZFSSA Node', 'Project'          ,'Share'           ,'StartTime'                ,'EndTime'                , 'DMA'                 );
  printf(FORMAT,'==========', '================' ,'===============' ,'========================' ,'=========================','====================' );
  var project='';
  var share='';
  var DMA='';
  var starttime='';
  var endtime='';
  for (i = 0; i < alerts.length; i++) 
  {
      run('select ' + alerts[i]);
      var msg=get('description');
      if ( msg.search(/An NDMP backup.*started/) > -1 )
      {
        project = msg.split(/'/)[3];
        share = msg.split(/'/)[1];
        DMA = msg.split(/'/)[5];
        starttime =  get('timestamp').toLocaleFormat(timestampformat).toUpperCase();
        endtime=''
      }
      if ( msg.search(/An NDMP backup has finished/) > -1 )
      {
         var msg_search_string = "share '" + share + "' in project '"  + project + "'"
         if (msg.search(msg_search_string)  > -1 ) 
         {
             endtime = get('timestamp').toLocaleFormat(timestampformat).toUpperCase();
         }      
          printf(FORMAT, ZFSSA_NODENAME, project, share, starttime, endtime, DMA);
      }
     run('cd ..');
  }
.



//#######################################
//# Show Audit Log
//#######################################
script
  var timestampformat='%Y-%m-%d %H:%M:%S (%Z)';
  run('cd /');
  run('maintenance logs select audit');
  alerts = list();
  var FORMAT='%-28s %-15s %-15s %-30s %-20s \n';
  printf(FORMAT,'Time'                     ,'User'             ,'Address'         , 'Summary'                 , 'Annotation');
  printf(FORMAT,'========================' ,'================' ,'================', '======================','================');
  for (i = 0; i < alerts.length; i++) 
  {
      run('select ' + alerts[i]);
      printf(FORMAT
           , get(' timestamp').toLocaleFormat(timestampformat).toUpperCase()
           , get('user')
           , get('address')
           , get('summary')
           , get('annotation')
           );
      run('cd ..');
  }
.


//#######################################
//# Storage Space Usage
//#######################################
script
  function BytesToString(bytes)
  {
        if      (bytes>=Math.pow(1024,5)) {bytes=(bytes/Math.pow(1024,5)).toFixed(2)+'PB';}
        else if (bytes>=Math.pow(1024,4)) {bytes=(bytes/Math.pow(1024,4)).toFixed(2)+'TB';}
        else if (bytes>=Math.pow(1024,3)) {bytes=(bytes/Math.pow(1024,3)).toFixed(2)+'GB';}
        else if (bytes>=Math.pow(1024,2)) {bytes=(bytes/Math.pow(1024,2)).toFixed(2)+'MB';}
        else if (bytes>=Math.pow(1024,1)) {bytes=(bytes/Math.pow(1024,1)).toFixed(2)+'KB';}
        else if (bytes>1)           {bytes=bytes+' bytes';}
        else if (bytes==1)          {bytes=bytes+' byte';}
        else                        {bytes='0 byte';}
        return bytes;
  }
     print('' );
     print('#############################' );
     print('# ZFS Appliance Space Usage #'   );
     print('#############################' );
     print('' );
     run('cd /');
     var ZFSSA_NODENAME =  run('configuration version get nodename').split(/\s+/)[3];
     run('status');
     run('storage');
     pools = list();
     for (i = 0; i < pools.length; i++) 
     {
         run('select ' + pools[i]);
         FORMAT1 = '%-15s: %10s\n';
         printf(FORMAT1,'ZFSSA NodeName',ZFSSA_NODENAME) ;
         printf(FORMAT1,'Pool',pools[i]) ;
         printf(FORMAT1,'State',get('state')) ;
         printf(FORMAT1,'Total',BytesToString(get('used') + get('avail'))) ;
         printf(FORMAT1,'Used',BytesToString(get('used'))) ;
         printf(FORMAT1,'Avail',BytesToString(get('avail'))) ;
         printf(FORMAT1,'Used%',(get('used')* 100  / (get('used') + get('avail')) ).toFixed(2) + '%') ;
         printf(FORMAT1,'Avail%',(get('avail')* 100  / (get('used') + get('avail')) ).toFixed(2) + '%') ;
         printf(FORMAT1,'Compression',get('compression') + 'x') ;
         printf(FORMAT1,'Dedup',get('dedup') + 'x') ;
         print('' );
         run('cd ..');
     }
.





//#######################################
//# List Projects
//#######################################
script
  function BytesToString(bytes)
  {
        if      (bytes>=Math.pow(1024,5)) {bytes=(bytes/Math.pow(1024,5)).toFixed(2)+'PB';}
        else if (bytes>=Math.pow(1024,4)) {bytes=(bytes/Math.pow(1024,4)).toFixed(2)+'TB';}
        else if (bytes>=Math.pow(1024,3)) {bytes=(bytes/Math.pow(1024,3)).toFixed(2)+'GB';}
        else if (bytes>=Math.pow(1024,2)) {bytes=(bytes/Math.pow(1024,2)).toFixed(2)+'MB';}
        else if (bytes>=Math.pow(1024,1)) {bytes=(bytes/Math.pow(1024,1)).toFixed(2)+'KB';}
        else if (bytes>1)           {bytes=bytes+'B';}
        else if (bytes==1)          {bytes=bytes+'B';}
        else                        {bytes='0';}
        return bytes;
  }
  function lpad(str, len, pad) {
      if (typeof(len) == "undefined") { var len = 0; }
      if (typeof(pad) == "undefined") { var pad = ' '; }
      if (len + 1 >= str.length) {
          str = Array(len + 1 - str.length).join(pad) + str;
      }
      return str;
  }
  function rpad(str, len, pad) {
      if (typeof(len) == "undefined") { var len = 0; }
      if (typeof(pad) == "undefined") { var pad = ' '; }
      if (len + 1 >= str.length) {
          str = str + Array(len + 1 - str.length).join(pad);
      }
      return str;
  }
  var timestampformat='%Y-%m-%d %H:%M:%S (%Z)';
  run('cd /');
  var ZFSSA_NODENAME =  run('configuration version get nodename').split(/\s+/)[3];
  run('cd /');
  run('shares');
  projects = list();
  print('##################################' );
  print('PROJECTS ' );
  print('##################################' );
  print('' );
  var    FORMAT='%-10s %-30s %-5s %-6s %-5s %-5s %-5s %-10s %-8s %-8s %-8s %-6s %-5s %-6s %-19s\n';
  printf(FORMAT,''          ,''               ,''     ,'Record' ,''     ,'Comp'  ,''     , ''           ,''         ,''         ,''         ,''      ,''     , ''       ,'Creation'             );
  printf(FORMAT,'ZFSSA Node','PROJECT'        ,'ATIME','Size'   ,'Comp' ,'Ratio' ,'Cache', 'LOGBIAS'    ,'TOTAL'    ,'DATA'     ,'SNAP'     ,'Shares','Snaps', 'Copies' ,'YYYY-MM-DD HH:MI:SS'  );
  printf(FORMAT,'==========','============='  ,'=====','======' ,'====' ,'=====' ,'=====', '==========' ,'========' ,'========' ,'========' ,'======','=====', '======' ,'=====================');
  for (i = 0; i < projects.length; i++) 
  {
      run('select ' + projects[i]);
      run('snapshots');
      snapshots = list();
      var noof_snapshots = 0;
      noof_snapshots = snapshots.length;
      run('cd ..');
      shares = list();
      var noof_shares = 0;
      noof_shares = shares.length;
      printf(FORMAT
           , ZFSSA_NODENAME
           , projects[i] 
           , get('atime')
           , get('recordsize')
           , get('compression')
           , get('compressratio')
           , get('secondarycache')
           , get('logbias')
           , lpad(BytesToString(get('space_total')),8)
           , lpad(BytesToString(get('space_data')),8)
           , lpad(BytesToString(get('space_snapshots')),8)
           , noof_shares
           , noof_snapshots
           , get('copies')
           , get('creation').toLocaleFormat(timestampformat).toUpperCase()
           );
      run('cd ..');
  }
.


//#######################################
//# Projects Cleanup
//#######################################

script
     run('cd /');
     var ZFSSA_NODENAME =  run('configuration version get nodename').split(/\s+/)[3];
     run('cd /');
     run('shares');
     projects = list();
     print('##################################' );
     print('PROJECTS ' );
     print('##################################' );
     print('' );
     var    FORMAT='%-10s %-30s %-7s %-7s %-7s %-6s %-5s %-6s %-20s %-30s\n';
     printf(FORMAT,'ZFSSA Node','PROJECT'        ,'TOTAL' ,'DATA' ,'SNAP' ,'Shares','Snaps', 'Copies' ,'Creation' , 'Command' );
     printf(FORMAT,'==========','============='  ,'=====' ,'====' ,'====' ,'======','=====', '======' ,'========' , '=======');
     for (i = 0; i < projects.length; i++) 
     {
        if ( projects[i].search('CLONE_') > -1 )
         {
               run('select ' + projects[i]);
               run('snapshots');
               snapshots = list();
               var noof_snapshots = 0;
               if ( snapshots.length > 0 ) {
                 noof_snapshots = snapshots.length;
               } 
               run('cd ..');
               shares = list();
               var noof_shares = 0;
               if ( shares.length > 0 ) {
                 noof_shares = shares.length;
               } 
               creation=run('get creation').split(/=/)[1].split(/\n/)[0].substr(1);
               creation=creation.split(/\s+/)[2] + '-' + creation.split(/\s+/)[1] + '-' + creation.split(/\s+/)[3] + ' ' + creation.split(/\s+/)[4] + ' ' + creation.split(/\s+/)[5];
               printf(FORMAT
                    , ZFSSA_NODENAME
                    , projects[i] 
                    , run('get space_total').split(/\s+/)[3]
                    , run('get space_data').split(/\s+/)[3]
                    , run('get space_snapshots').split(/\s+/)[3]
                    , noof_shares
                    , noof_snapshots
                    , run('get copies').split(/\s+/)[3]
                    , creation
                    , 'confirm shares destroy ' + projects[i] 
                    );
              run('cd ..');
         }           
     }
.






//#######################################
//# List Automatic Snapshot Schedules
//#######################################
script
       run('cd /');
       var ZFSSA_NODENAME =  run('configuration version get nodename').split(/\s+/)[3];
       run('shares');
       var pool =  run('get pool').split(/\s+/)[3];
       projects = list();
       print ('################################');
       print ('# Automatic Snapshot Schedules #');
       print ('################################');
       print('' );
       var FORMAT='%-10s %-10s %-30s %-30s %-9s %-9s %-5s %-5s\n';
       printf(FORMAT, 'ZFSSA Node' , 'POOL'   , 'PROJECT'       , 'AutoSchedule'   , 'FREQUENCY', 'DAY'      , 'HH:MM' ,'KEEP');
       printf(FORMAT, '==========' , '=======', '==============', '===============', '=========', '=========', '=====' ,'====');
       for (i = 0; i < projects.length; i++) 
       {
            run('select ' + projects[i]);
            run('snapshots automatic');
            autoschedule = list();
            if (autoschedule.length > 0 ) 
            {
                for (j = 0; j < autoschedule.length; j++) 
                {
                        run('select ' + autoschedule[j]);
                        printf(FORMAT
                              , ZFSSA_NODENAME
                              , pool
                              , projects[i]
                              , autoschedule[j]
                              , run('get frequency').split(/\s+/)[3]
                              , run('get day').split(/\s+/)[3]
                              , run('get hour').split(/\s+/)[3] + ':' + run('get minute').split(/\s+/)[3]
                              , run('get keep').split(/\s+/)[3]
                             );
                        run('cd ..');
                }
            }    
            run('cd ..');
            run('cd ..');
            run('cd ..');
       }
.


//#######################################
//# List Snapshot Info (Project Level)
//#######################################
script
       print ('#################################');
       print ('# Snapshot Info (Project Level) #');
       print ('#################################');
       print('' );
       run('cd /');
       var ZFSSA_NODENAME =  run('configuration version get nodename').split(/\s+/)[3];
       run('shares');
       projects = list();
       var FORMAT='%-10s %-10s %-30s %-30s %-6s %-6s %-12s %-19s\n';
       printf(FORMAT, 'ZFSSA Node' , 'POOL'   , 'PROJECT'       , 'SNAPSHOT'       , 'ISAUTO', 'Clones', 'UniqueSpace', 'Creation');
       printf(FORMAT, '==========' , '=======', '==============', '===============', '======', '======', '===========', '=====================');
       for (i = 0; i < projects.length; i++) 
       {
            run('select ' + projects[i]);
            run('snapshots');
            snapshots = list();
            if (snapshots.length > 0 ) 
            {
                for (j = 0; j < snapshots.length; j++) 
                {
                        run('select ' + snapshots[j]);
                        creation=run('get creation').split(/=/)[1].split(/\n/)[0].substr(1);
                        creation=creation.split(/\s+/)[2] + '-' + creation.split(/\s+/)[1] + '-' + creation.split(/\s+/)[3] + ' ' + creation.split(/\s+/)[4] + ' ' + creation.split(/\s+/)[5];
                        printf(FORMAT
                              , ZFSSA_NODENAME
                              , run('get pool').split(/\s+/)[3]
                              , projects[i]
                              , snapshots[j]
                              , run('get isauto').split(/\s+/)[3]
                              , run('get numclones').split(/\s+/)[3]
                              , run('get space_unique').split(/\s+/)[3]
                              , creation
                             );
                        run('cd ..');
                }
            }    
            run('cd ..');
            run('cd ..');
       }
.



//#######################################
//# Project Snapshot Cleanup
//#######################################
script
       run('cd /');
       var ZFSSA_NODENAME =  run('configuration version get nodename').split(/\s+/)[3];
       run('shares');
       projects = list();
       print ('############################');
       print ('# Project Snapshot Cleanup #');
       print ('############################');
       print('' );
       var FORMAT='%-10s %-10s %-30s %-60s\n';
       printf(FORMAT, 'ZFSSA Node' , 'POOL'   , 'Creation'           ,'Command');
       printf(FORMAT, '==========' , '=======', '==================' ,'========================================');
       for (i = 0; i < projects.length; i++) 
       {
            run('select ' + projects[i]);
            run('snapshots');
            snapshots = list();
            if (snapshots.length > 0 ) 
            {
                for (j = 0; j < snapshots.length; j++) 
                {
                    //if (  )
                    if ( snapshots[j].search('SNAP_') > -1 || snapshots[j].search('AL06') > -1  )
                     {
                        run('select ' + snapshots[j]);
                        creation=run('get creation').split(/=/)[1].split(/\n/)[0].substr(1);
                        creation=creation.split(/\s+/)[2] + '-' + creation.split(/\s+/)[1] + '-' + creation.split(/\s+/)[3] + ' ' + creation.split(/\s+/)[4] + ' ' + creation.split(/\s+/)[5];
                        printf(FORMAT
                              , ZFSSA_NODENAME
                              , run('get pool').split(/\s+/)[3]
                              , creation
                              , 'confirm shares select ' + projects[i] + ' snapshots destroy ' + snapshots[j] 
                             );
                        run('cd ..');
                     }
                }
            }    
            run('cd ..');
            run('cd ..');
       }
.


//#######################################
//# Shares Info
//#######################################
script
       print('##################################' );
       print('Shares Info ' );
       print('##################################' );
       print('' );
       run('cd /');
       run('shares');
       projects = list();
       var FORMAT='%-40s %-30s %-5s %-5s %-9s %-10s %-7s %-7s %-7s %-5s %-7s %-19s\n';
       printf(FORMAT ,'SHARE'       , 'MOUNTPOINT', 'ATIME', 'Comp', 'CompRatio', 'LOGBIAS', 'TOTAL', 'DATA', 'SNAP', 'Snaps', 'COPIES', 'Creation');
       printf(FORMAT, '============', '==========', '=====', '====', '=========', '=======', '=====', '====', '====', '=====', '======', '=========================');
       for (i = 0; i < projects.length; i++) 
       {
          run('select ' + projects[i]);
          shares = list();
          if ( shares.length > 0 )
          {
              for (j = 0; j < shares.length; j++) 
              {
                run('select ' + shares[j]);
                run('snapshots');
                snapshots = list();
                var noof_snapshots = 0;
                if ( snapshots.length > 0 ) {
                  noof_snapshots = snapshots.length;
                } 
                run('cd ..');
                creation=run('get creation').split(/=/)[1].split(/\n/)[0].substr(1);
                creation=creation.split(/\s+/)[3] + '-' + creation.split(/\s+/)[2] + '-' + creation.split(/\s+/)[4] + ' ' + creation.split(/\s+/)[5] ;
                printf(FORMAT
                     , projects[i] + '/' + shares[j]
                     , run('get mountpoint').split(/\s+/)[3]
                     , run('get atime').split(/\s+/)[3]
                     , run('get compression').split(/\s+/)[3]
                     , run('get compressratio').split(/\s+/)[3]
                     , run('get logbias').split(/\s+/)[3]
                     , run('get space_total').split(/\s+/)[3]  
                     , run('get space_data').split(/\s+/)[3]
                     , run('get space_snapshots').split(/\s+/)[3]
                     , noof_snapshots
                     , run('get copies').split(/\s+/)[3]
                     , creation
                     );
                run('cd ..');
              }
          }
          run('cd ..');
       }
.


//#######################################
//# List Snapshot Info (Share Level)
//#######################################
script
       print ('#################################');
       print ('# Snapshot Info (Share Level)   #');
       print ('#################################');
       print('' );
       run('cd /');
       run('shares');
       projects = list();
       var FORMAT='%-10s %-30s %-15s %-7s %-25s %-6s %-6s %-6s %-19s\n';
       printf(FORMAT, ''       , ''              , ''              , 'Snap'  , ''               , ''      , ''       , 'Unique' , ''        );
       printf(FORMAT, 'POOL'   , 'PROJECT'       , 'SHARE'         , 'Level' , 'SNAPSHOT'       , 'ISAUTO', 'Clones' , 'Space'  , 'Creation');
       printf(FORMAT, '=======', '==============', '==============', '=====' , '===============', '======', '======' , '======' , '=====================');
       for (i = 0; i < projects.length; i++) 
       {
          run('select ' + projects[i]);
          shares = list();
          if (shares.length > 0 ) 
          {
               for (j = 0; j < shares.length; j++) 
               {
                   run('select ' + shares[j]);
                   run('snapshots');
                   snapshots = list();
                   if (snapshots.length > 0 ) 
                   {
                        for (k = 0; k < snapshots.length; k++) 
                        {
                             var snaplevel = '';
                             run('select ' + snapshots[k]);
                             run('cd ..');
                             run('cd ..');
                             run('cd ..');
                             run('snapshots');
                             try {
                                  run('select ' + snapshots[k] );
                                  run('cd ..');
                                   snaplevel = 'Project';
                             } catch (err) {
                                 snaplevel = 'Share';
                               }
                             run('cd ..');
                             run('select ' + shares[j]);
                             run('snapshots');
                             run('select ' + snapshots[k]);
                             creation=run('get creation').split(/=/)[1].split(/\n/)[0].substr(1);
                             creation=creation.split(/\s+/)[3] + '-' + creation.split(/\s+/)[2] + '-' + creation.split(/\s+/)[4] + ' ' + creation.split(/\s+/)[5] ;
                             if ( snaplevel != 'Project' ) {
                               printf(FORMAT
                                     , run('get pool').split(/\s+/)[3]
                                     , projects[i]
                                     , shares[j]
                                     , snaplevel
                                     , snapshots[k]
                                     , run('get isauto').split(/\s+/)[3]
                                     , run('get numclones').split(/\s+/)[3]
                                     , run('get space_unique').split(/\s+/)[3]
                                     , creation
                                    );
                             }     
                             run('cd ..');
                        }
                   }
                   run('cd ..');
                   run('cd ..');
               }
          }
          run('cd ..');
       }
.




//#######################################
//# List Analytic Worksheets
//#######################################
script
       print ('#########################');
       print ('# Analytic Worksheets   #');
       print ('#########################');
       print('' );
       var WORKSHEET_FORMAT='%-10s %-35s %-7s %-20s %-20s %-20s\n';
       printf(WORKSHEET_FORMAT, 'ZFSSA Node' , 'Worksheet Name' ,'Seconds','Owner','Modified','Created');
       printf(WORKSHEET_FORMAT, '==========' , '==============' ,'=======','=====','========','=======');
       run('cd /');
       var ZFSSA_NODENAME =  run('configuration version get nodename').split(/\s+/)[3];
       run('analytics worksheets');
       worksheets = list();
       for (i = 0; i < worksheets.length; i++) 
       {
            run('select ' + worksheets[i]);
            name = run('get name').split(/=/)[1].split(/\n/)[0].substr(1);
            owner = run('get owner').split(/=/)[1].split(/\n/)[0].substr(1);
            ctime = run('get ctime').split(/=/)[1].split(/\n/)[0].substr(1);
            mtime = run('get mtime').split(/=/)[1].split(/\n/)[0].substr(1);
            printf(WORKSHEET_FORMAT
                 , ZFSSA_NODENAME
                 , name
                 , ' '
                 , owner
                 , mtime
                 , ctime
                  );
            datasets = list();
            var DATASET_FORMAT='%-15s %-30s %-20s\n';
            for (j = 0; j < datasets.length; j++) 
            {
               run('select ' + datasets[j]);
               printf(DATASET_FORMAT
                    , ' '
                    , run('get name').split(/=/)[1].split(/\n/)[0].substr(1)
                    , run('get seconds').split(/=/)[1].split(/\n/)[0].substr(1)
                    );
               run('done');
           }    
           print('');           
           run('done');
     }
.



//#######################################
//# List Analytic Datasets
//#######################################
script
       print ('#########################');
       print ('# Analytic Datasets     #');
       print ('#########################');
       print('' );
       run('cd /');
       var ZFSSA_NODENAME =  run('configuration version get nodename').split(/\s+/)[3];
       run('analytics settings');
       print('Settings:' );
       print(run('get retain_second_data'));
       print(run('get retain_minute_data'));
       print(run('get retain_hour_data'));
       print('' );
       var FORMAT='%-10s %-11s %-10s %-10s %-6s %-6s %-10s %-40s %-40s \n';
       printf(FORMAT, 'ZFSSA Node' , 'Dataset ID' ,'Grouping','State'   ,'InCore' ,'OnDisk','Activity'  ,'Dataset Name'           ,'Description');
       printf(FORMAT, '==========' , '==========' ,'========','========','======','======','==========','=======================','=============================');
       run('cd /');
       run('analytics datasets');
       datasets = list();
       for (i = 0; i < datasets.length; i++) 
       {
          run('select ' + datasets[i]);
          var state;
          if ( run('get suspended').split(/\s+/)[3] == 'true')  { state  = 'Suspended';}
          else { state  = 'Active';}
          //if ( state = 'Active' )
          //{
             printf(FORMAT
                  , ZFSSA_NODENAME
                  , datasets[i]
                  , run('get grouping').split(/\s+/)[3]
                  , state
                  , run('get incore').split(/\s+/)[3]
                  , run('get size').split(/\s+/)[3]
                  , run('get activity').split(/\s+/)[3]
                  , run('get name').split(/\s+/)[3]
                  , run('get explanation').split(/=/)[1].split(/\n/)[0].substr(1)
                  );
          //}       
          run('cd ..');
       }
.


//#######################################
//# Display ZFS Statistics
//#######################################

script 
    print ('#########################');
    print ('# Analytic Datasets     #');
    print ('#########################');
    print('' );
    var dataset_name = 'ip.bytes[hostname]';
    var seconds_to_read = 10;
    var datetime;
    var ZFSSA_NODENAME;
    var value;
    var breakdown;
    run('cd /');
    ZFSSA_NODENAME = run('configuration version get nodename').split(/\s+/)[3].toLowerCase();
    run('cd /');
    run('analytics datasets');
    datasets = list();
    for (f = 0; f < datasets.length; f++) 
    {
       run('select ' + datasets[f]);
       name = run('get name').split(/\s+/)[3];
       //print (name);
       if ( name == dataset_name ) 
       {
          // Get last N seconds data including breakdown and iterate through line
          line = run('read ' + seconds_to_read).split(/\n/);
          for (i = 0; i<line.length; i++) 
          {
             value = '';
             breakdown = '';
             // Iterate through words in each line
             column = line[i].split(/\s+/);
             // Ignore head line
             if ( column[0] != 'DATE/TIME' || column[0] == '' )
             {
                 //New time line
                 if ( column[0] =~ '2014' &&  column[0] != '')  
                 {
                     datetime = line[i].split(/\s+/)[0] + ' ' + column[1];
                     value = column[3];
                     breakdown = column[4];
                     //dump(line[i]);
                     //print(datetime + ' '+ value + ' ' + breakdown);    
                 }
                 else
                 {
                     value = column[1];
                     breakdown = column[2];
                     //dump(line[i]);
                     //print(value + ' ' + breakdown);    
                 }
                 // Only print values if variables are defined
                 if ( datetime && value && breakdown)   
                 {
                     print(datetime + ' ' + value + ' ' + breakdown);    
                 }
               }
           }
       }
      run('cd ..');
    }
.


   

//#######################################
//# List Hardware info
//#######################################
script
       run('cd /');
       var ZFSSA_NODENAME =  run('configuration version get nodename').split(/\s+/)[3];
       print ('#########################');
       print ('# Project Snapshot Info #');
       print ('#########################');
       print('' );
       run('maintenance hardware');
       run('select chassis-000' ); 
       print('Name         : ' + run('get name').split(/=/)[1].split(/\n/)[0].substr(1) );
       print('Manufacturer : ' + run('get manufacturer').split(/=/)[1].split(/\n/)[0].substr(1) );
       print('Model        : ' + run('get model').split(/=/)[1].split(/\n/)[0].substr(1) );
       print('Serial       : ' + run('get serial').split(/=/)[1].split(/\n/)[0].substr(1) );
           run('select cpu');
           cpu = list();
               run('select ' + cpu[0]);
               print('Processors   : ' + (cpu.length) 
                                       + 'x ' 
                                       + run('get speed').split(/=/)[1].split(/\n/)[0].substr(1)
                                       + ' ' 
                                       //+ run('get model').split(/=/)[1].split(/\n/)[0].substr(1) 
                      );
               run('done');
           run('done');

           run('select memory');
           cpu = list();
               run('select ' + cpu[0]);
               print('Processors   : ' + (cpu.length) 
                                       + 'x ' 
                                       + run('get speed').split(/=/)[1].split(/\n/)[0].substr(1)
                                       + ' ' 
                                       + run('get model').split(/=/)[1].split(/\n/)[0].substr(1) );
               run('done');
           run('done');
       run('done');
       print(' ');
       print(' ');
/*
       var FORMAT='%-10s %-11s %-10s %-10s %-7s %-25s %-25s %-10s %-10s\n';
       printf(FORMAT, 'ZFSSA Node' ,o 'Chassis', 'Type'  , 'Name'  , 'State' , 'Manufacturer' , 'Model'    , 'Serial' , 'Locate' );
       printf(FORMAT, '==========' , '=======', '=====' , '=====' , '=====' , '============' , '=========', '======' , '====='  );
       chassis = list();
       for (i = 1; i < chassis.length; i++) 
       {
          run('select ' + chassis[i]);
          faulted = run('get faulted').split(/\s+/)[3];
          if ( faulted == 'false' ) { state = 'ok' }
          else { state = 'faulted' }
          printf(FORMAT
               , ZFSSA_NODENAME
               , chassis[i]
               , run('get type').split(/=/)[1].split(/\n/)[0].substr(1)
               , run('get name').split(/=/)[1].split(/\n/)[0].substr(1)
               , state
               , run('get manufacturer').split(/=/)[1].split(/\n/)[0].substr(1)
               , run('get model').split(/=/)[1].split(/\n/)[0].substr(1)
               , run('get serial').split(/=/)[1].split(/\n/)[0].substr(1)
               , run('get locate').split(/=/)[1].split(/\n/)[0].substr(1)
               );
          run('done');
       }
*/       
.


         creation=run('get creation').split(/=/)[1].split(/\n/)[0].substr(1);
         creation=creation.split(/\s+/)[2] + '-' + creation.split(/\s+/)[1] + '-' + creation.split(/\s+/)[3] + ' ' + creation.split(/\s+/)[4] + ' ' + creation.split(/\s+/)[5];



//########################################################
//#  Delete snapshots and clone older than a date
//########################################################
script
    var threshold_date='20140922';
    var SNAPNAME_PREFIX1='SNAP_';
    var SNAPNAME_PREFIX2='AL06PIMI_';
    var CLONENAME_PREFIX='CLONE_';
    run('cd /');
    ZFSSA_NODENAME =  run('configuration version get nodename').split(/\s+/)[3];
    run('shares');
    projects = list();
    print ('##################################');
    print ('# Older Clone/Snapshost Clean-up #');
    print ('##################################');
    print('' );
    function dateToString(inDate)
    {
        year  = inDate.getUTCFullYear().toString();
        // Month returned is from 0 - 11, so need to add 1
        month = inDate.getUTCMonth() + 1;
        month = month.toString();
        date  = inDate.getUTCDate().toString();

        outDate = year;
        
        if ( month.length == 1 )
        {  outDate =  outDate + '0' + month; }
        else {   outDate =  outDate + month; }

        if ( date.length == 1 )
        {  outDate =  outDate + '0' + date; }
        else {   outDate =  outDate + date; }
        return outDate;
    }
    var FORMAT='%-10s %-10s %-40s %-60s\n';
    printf(FORMAT, 'ZFSSA Node' , 'POOL'   , 'Creation'           ,'Command');
    printf(FORMAT, '==========' , '=======', '==================' ,'========================================');
    for (i = 0; i < projects.length; i++) 
    {
         run('cd /');
         run('shares');
         run('select ' + projects[i]);
         if ( projects[i].search(CLONENAME_PREFIX) > -1 )
         {
             creation = dateToString(get('creation'));
             if ( creation < threshold_date )
             {
              printf(FORMAT
                    , ZFSSA_NODENAME
                    , run('get pool').split(/\s+/)[3]
                    , get('creation')
                    , 'confirm shares destroy ' + projects[i] 
                   );
             }      
         }    
         run('snapshots');
         snapshots = list();
         if (snapshots.length > 0 ) 
         {
             for (j = 0; j < snapshots.length; j++) 
             {
                 if ( snapshots[j].search(SNAPNAME_PREFIX1) > -1 || snapshots[j].search(SNAPNAME_PREFIX2) > -1 )
                  {
                    run('select ' + snapshots[j] );
                    creation = dateToString(get('creation'));
                    if ( creation < threshold_date )
                    {
                     printf(FORMAT
                           , ZFSSA_NODENAME
                           , run('get pool').split(/\s+/)[3]
                           , get('creation')
                           , 'confirm shares select ' + projects[i] + ' snapshots destroy ' + snapshots[j]
                          );
                    }      
                    run('cd ..');
                  }       
             }
         }    
    }
.





//########################################################
//#  Scratchpad
//########################################################
script
print(get('creation').getUTCDate().toString() );
print(get('creation').toDateString() );
.


script
creation = get('creation').getUTCFullYear().valueOf();
if ( get('creation').getUTCMonth().toString().length == 1 )
{  creation =  creation + '0' + get('creation').getUTCMonth(); }
else {   creation =  creation + get('creation').getUTCMonth(); }

if ( get('creation').getUTCDate().toString().length == 1 )
{  creation =  creation + '0' + get('creation').getUTCDate(); }
else {   creation =  creation + get('creation').getUTCDate(); }

if ( creation > '20140910') 
{ print(creation + ' date is older');}
else
{ print(creation +' date is new');}
.


script
var mydate= new Date();
var mydate2= new Date();
print(mydate.toString());
print(mydate2.toString());
mydate2 = mydate2.toString() - 10;
print(mydate2.toString());
.



script
   function SuffixToMultiplier(suffix)
    {
       switch (suffix)
       {
         case('K'): return  Math.pow(1024,1); break;
         case('M'): return  Math.pow(1024,2); break;
         case('G'): return  Math.pow(1024,3); break;
         case('T'): return  Math.pow(1024,4); break;
         case('P'): return  Math.pow(1024,5); break;
         default:   return  1; break;
       }
    }

    function StringtoBytes(value)
    {
      if ( value.charAt(value.length-1). )
      {
          return value.substr(0,value.length - 1) * SuffixToMultiplier(value.charAt(value.length-1));
      }
    }

.


script
  function BytesToString(bytes)
  {
        if      (bytes>=Math.pow(1024,5)) {bytes=(bytes/Math.pow(1024,5)).toFixed(2)+' PB';}
        else if (bytes>=Math.pow(1024,4)) {bytes=(bytes/Math.pow(1024,4)).toFixed(2)+' TB';}
        else if (bytes>=Math.pow(1024,3)) {bytes=(bytes/Math.pow(1024,3)).toFixed(2)+' GB';}
        else if (bytes>=Math.pow(1024,2)) {bytes=(bytes/Math.pow(1024,2)).toFixed(2)+' MB';}
        else if (bytes>=Math.pow(1024,1)) {bytes=(bytes/Math.pow(1024,1)).toFixed(2)+' KB';}
        else if (bytes>1)           {bytes=bytes+' bytes';}
        else if (bytes==1)          {bytes=bytes+' byte';}
        else                        {bytes='0 byte';}
        return bytes;
  }
  print (BytesToString(102345000000000667));
  print (BytesToString(10125));
.



