#
# this patch to the pure UUID generator found @
# http://mput.dip.jp/mput/uuid.txt adds auto macaddr detection and stores the
# state in the db for use in rails projects.
#

class UUID
  class << self
    if defined? Rails
       UUID::Model =
        Class.new(ActiveRecord::Base) do
          set_table_name 'uuid'
          set_primary_key 'uuid_id'
        end

       require 'macaddr'  ### gem install macaddr

       alias_method "create_file", "create"
       def create clock=nil, time=nil, mac_addr=Mac.addr
          c = t = m = nil

          #uuid = UUID.
          uuid = Model.find :first

          unless uuid
            m = mac_addr
            c = rand 0x40000
            uuid = Model.new :clock => c, :mac_addr => m
            uuid.save!
            uuid.update
          end

          c, m = uuid.clock, uuid.mac_addr

          c = clock % 0x4000 if clock
          m = mac_addr if mac_addr
          t = time
          if t.nil? then
             # UUID epoch is 1582/Oct/15
             tt = Time.now
             t = tt.to_i*10000000 + tt.tv_usec*10 + 0x01B21DD213814000
          end
          c = c.succ # important; increment here

          uuid.clock = c
          uuid.mac_addr = m
          uuid.save!
          uuid.update

          tl = t & 0xFFFF_FFFF
          tm = t >> 32
          tm = tm & 0xFFFF
          th = t >> 48
          th = th & 0x0FFF
          th = th | 0x1000
          cl = c & 0xFF
          ch = c & 0x3F00
          ch = ch >> 8
          ch = ch | 0x80
          pack tl, tm, th, cl, ch, m
       end
       alias_method "next", "create"
    end
  end
end