# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Mobius Forensic Toolkit
# Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019 Eduardo Aguiar
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
import mobius
import binascii

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# @brief Entry
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
class Entry (object):

  # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  # @brief initialize object
  # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  def __init__ (self):
    self.hash_sha1 = None
    self.hashes = []

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# @brief Decode PHashIdx.dat file
# @see ICH_load_phash_index - helper_ICH.pas (line 1024)
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
def decode (f):

  reader = f.new_reader ()
  if not reader:
    return

  # check signature
  decoder = mobius.decoder.data_decoder (reader)
  signature = decoder.get_string_by_size (14)

  if signature != '__ARESDBP102__':
    return

  # get file metadata
  phashidx_path = f.path.replace ('/', '\\')
  phashidx_creation_time = f.creation_time
  phashidx_last_modification_time = f.last_modification_time

  # decode entries
  entries = []
  pos = decoder.tell ()
  size = decoder.get_size ()
  idx = 0
  
  while pos < size:
    entry = Entry ()
    entry.idx = idx
    entry.phashidx_path = phashidx_path
    entry.phashidx_creation_time = phashidx_creation_time
    entry.phashidx_last_modification_time = phashidx_last_modification_time

    num64 = decoder.get_uint64_le ()
    item_size = decoder.get_uint32_le ()
    entry.hash_sha1 = binascii.hexlify (decoder.get_bytearray_by_size (20))
    num32 = decoder.get_uint32_le ()

    for i in xrange (item_size // 20):
      h = binascii.hexlify (decoder.get_bytearray_by_size (20))
      entry.hashes.append (h)

    entries.append (entry)
    pos = decoder.tell ()
    idx += 1

  return entries
