#!/usr/bin/env python

# Securely write timestamped marker files
# 
# 
# This script is not really usable without prior modification, due to hardcoded
# path names and user/group IDs. Thus, you have to edit it for your needs.
# 
# One thing that is special is that the files ending in "invisible" will be made
# mode 0640, others 0644.
#
#
# 
# Copyright 2008,2009 Peter Poeml <poeml@cmdline.net>, Novell Inc.
# Copyright 2008-2014 Peter Poeml <poeml@cmdline.net>
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 2
# as published by the Free Software Foundation;
# 
# 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA



import os
import sys
import time
import tempfile
import pwd, grp

epoch = int(time.time())
utc = time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime())

explanation = """
Should you wonder about this file, it supplies timestamps that can be
used to assess possible lags in mirroring.

These are not used by MirrorBrain for mirror checking, but can help
human beings with verifying a mirrors setup. (Maybe MirrorBrain could/should
make use of these timestamps in the future.)

In addition, the .timestamp_invisible is supposed to be not visible
through HTTP, FTP or rsync. This serves to ensure that a mirrors's
permission setup is correct. Keeping certain files temporarily
unreadable can be an important step in the process of publishing content.

Feel free to contact mirrorbrain at mirrorbrain org for more information;
Thanks.

"""


if len(sys.argv) < 2:
    sys.exit("""Missing argument.
Usage: 

  %s [username:groupname] timestampfile1 [timestampfile2...]
""" % os.path.basename(sys.argv[0]))

if not '/' in sys.argv[1] and ':' in sys.argv[1]:
    user, group = sys.argv[1].split(':')
    user = pwd.getpwnam(user).pw_uid 
    group = grp.getgrnam(group).gr_gid
    tstamps = sys.argv[2:]
else:
    user = os.geteuid()
    group = os.getegid()
    tstamps = sys.argv[1:]

for tstamp in tstamps:
    # we might write in a directory not owned by root
    (fd, tmpfilename) = tempfile.mkstemp(prefix = os.path.basename(tstamp), 
                                         dir = os.path.dirname(tstamp))

    if tstamp.endswith('invisible'):
        mode = 0640
    else:
        mode = 0644

    os.chown(tmpfilename, 
             user, 
             group)

    os.chmod(tmpfilename, mode)
    
    f = os.fdopen(fd, 'w')
    f.write('%s\n%s\n\n' % (epoch, utc))
    f.write(explanation)
    f.close()

    os.rename(tmpfilename, tstamp)

