#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#***********************************************************************
# This file is part of OpenMolcas.                                     *
#                                                                      *
# OpenMolcas is free software; you can redistribute it and/or modify   *
# it under the terms of the GNU Lesser General Public License, v. 2.1. *
# OpenMolcas is distributed in the hope that it will be useful, but it *
# is provided "as is" and without any express or implied warranties.   *
# For more details see the full text of the license in the file        *
# LICENSE or in <http://www.gnu.org/licenses/>.                        *
#                                                                      *
# Copyright (C) 2013, Steven Vancoillie                                *
#               2020, Ignacio Fdez. Galván                             *
#***********************************************************************
#
# setmtime
#
# Program that sets the last access/modification times
# of all files in a directory (default is the git work
# tree) to the time of the last commit before a certain
# commit (default is HEAD).
#
# By design, git does not keep track of metadata such as
# last modification time (for several reasons), so one
# has to extract this from the history of the git repo.
#
# Used with OpenMolcas to set modification times of all files
# in an exported snapshot, e.g. executing the following
# command inside a OpenMolcas git repository:
#   $ sbin/setmtime /tmp/snapshot daily-snapshot
# would set the times of all files under /tmp/snapshot to
# the latest commit date up to daily-snapshot.
#
# Steven Vancoillie, July 2013
#
# Ignacio Fdez. Galván, 2020: Translated from Perl to Python

import sys
import os
import subprocess as sp

thisfile = os.path.basename(__file__)
MOLCAS_DRIVER = os.environ.get('MOLCAS_DRIVER', 'pymolcas')
DRIVER_base = os.path.basename(MOLCAS_DRIVER)

try:
  MOLCAS = os.environ['MOLCAS']
except KeyError:
  sys.exit('MOLCAS not set, use {} {}'.format(DRIVER_base, thisfile))

# if this is a git repo, sanity check if git exists,
# otherwise print a warning.
try:
  sp.check_call(['git', '-C', MOLCAS, 'rev-parse', '--git-dir'], stdout=sp.PIPE, stderr=sp.STDOUT)
except:
  print('Error: git not available or not a git repo')
  sys.exit(1)

# parse options

n_args = len(sys.argv)
if n_args == 2:
  directory = sys.argv[1]
  snapshot = 'HEAD'
elif n_args == 3:
  directory = sys.argv[1]
  snapshot = sys.argv[2]
else:
  print('Error: invalid number of arguments to {}'.format(thisfile))
  sys.exit(1)

# git a list of access times and files
seen = []
logbook = sp.check_output(['git', 'log', '--raw', '--no-merges', '--pretty=%at', snapshot]).decode()
for line in logbook.split('\n'):
  if line.strip() == '':
    continue
  if line.startswith(':'):
    filename = line.split('\t')[1].rstrip()
    if filename in seen:
      continue
    dst = os.path.join(directory, filename)
    if os.path.isfile(dst):
      os.utime(dst, times=(timestamp, timestamp))
    seen.append(filename)
  else:
    timestamp = int(line)
