#!/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,2010 Peter Poeml <poeml@cmdline.net>, Novell Inc.
# 
# 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 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 serves as timestamp that can be
used to assess possible lags in mirroring.

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 is an important step in the process of publishing content.

Feel free to contact admin at opensuse org for more information!
Thanks.

"""


tstamps = [ '/srv/ftp/pub/opensuse/distribution/.timestamp',
            '/srv/ftp/pub/opensuse/distribution/.timestamp_invisible',
            '/srv/ftp-stage/pub/opensuse/distribution/.timestamp',
            '/srv/ftp-stage/pub/opensuse/distribution/.timestamp_invisible' ]


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 'ftp-stage' in tstamp:
        group = 'stage'
    else:
        group = 'nogroup'

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

    os.chown(tmpfilename, 
             pwd.getpwnam('mirror').pw_uid, 
             grp.getgrnam(group).gr_gid)

    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)

