#!/usr/bin/env python

"""
Securely write timestamped marker files

The files ending in "invisible" will be made mode 0640, others 0644.

This script is not usable without prior modification, due to hardcoded path
names and user/group IDs.

Peter Poeml <poeml@suse.de>


Copyright (C) 2006 Peter Poeml / Novell Inc.  All rights reserved.
This program is free software; it may be used, copied, modified
and distributed under the terms of the GNU General Public Licence,
either version 2, or (at your option) any later version.
"""

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)

