#!/usr/bin/ruby
#
# File epochsec2vars.rb
#
# Utility to rename files named with epoch seconds to files renamed by
# replacing the epoch seconds portion with the YYMMDD-hhmmss format
# favored by VARS.
#
# Example:
#    $ epochsec2vars.rb  fluoro_ext_1234567890.34.tiff
#    fluoro_ext_1234567890.34.tiff => fluoro_ext_090213-153130.tiff
#
# (1) Split the original name into dirname, basename, and extname
# (2) Further split the basename by '_', look for a section with epoch seconds
# (3) Replace that section with the converted string
# (4) Recombine the basename by joining the components with '_'
# (5) Append extname to dirname and basename, and rename the file
#
require 'getoptlong'

# Helper methods
def usage()
   puts("")
   puts("Epochseconds to VARS standard file name conversion utility")
   puts("Usage:")
   puts("epochsec2vars file1  [file2...]")
   puts("")
   puts("Example:")
   puts("  $ epochsec2vars.rb  fluoro_ext_1234567890.34.tiff")
   puts("    fluoro_ext_1234567890.34.tiff => fluoro_ext_090213-153130.tiff")
   puts("")
end

# Main
#
# Get the options first, if any
#

# GetopLong shifts the arguments in ARGV, so now the only items
# left in the ARGV array are the filenames
#
if (ARGV.size == 0)
   usage()
   exit
end

# Process each filename in the argument list
#
ARGV.each do |src_filename|
   next unless File.file?(src_filename)  # Skip unless a regular file

   # Separate the filename parts
   #
   dir  = File.dirname(src_filename)
   base = File.basename(src_filename, ".*")
   ext  = File.extname(src_filename)

   # Split the base name by '_'
   baselist = base.split('_')
   # Determine which component to convert
   i = 0
   varsformat = ""
   converted = false
   baselist.each do |epochsecs|
      if (epochsecs.to_i > 1000000000)
         puts("Converting #{epochsecs}")
         tm = Time.at(epochsecs.to_i)
         varsformat = (tm.year % 1000).to_s
         varsformat += '0' if (tm.month < 10)
         varsformat += tm.month.to_s
         varsformat += tm.day.to_s + '-'
         varsformat += '0' if (tm.hour < 10)
         varsformat += tm.hour.to_s
         varsformat += '0' if (tm.min < 10)
         varsformat += tm.min.to_s
         varsformat += '0' if (tm.sec < 10)
         varsformat += tm.sec.to_s
         converted = true
         break
      end
      i += 1
   end

   # Maybe the source filename did not have epoch seconds
   if (converted)
      baselist[i] = varsformat
   else
      puts("Skipping #{src_filename}...")
      next
   end

   # Now construct the date and time parts of the filename
   #
   vars_filename = "#{dirname}/#{baselist.join("_")}#{ext}"

   # Rename the file
   #
   puts("epochsecs2vars: #{src_filename} -> #{vars_filename}")
   if (!File.exists?(vars_filename))
      File.rename(src_filename, vars_filename)
   else
      puts("tripod2vars: #{vars_filename} already exists here...keeping #{src_filename}")
   end
   #sleep(0.05)
end

