#!/usr/bin/env python
# Copyright (c) 2005-2006 XenSource, Inc. All use and distribution of this 
# copyrighted material is governed by and subject to terms and conditions 
# as licensed by XenSource, Inc. All other rights reserved.
# Xen, XenSource and XenEnterprise are either registered trademarks or 
# trademarks of XenSource Inc. in the United States and/or other countries.

###
# TIME UTILITY
# For use by clean installer so that we can avoid uClibc's 
# time functions.
#
# written by Andrew Peace

import sys
import os
import datetime
import time

def getLocalNow(timezone = None):
    if timezone:
        os.environ['TZ'] = timezone
        time.tzset()

    now = datetime.datetime.now()
    
    second = now.second
    minute = now.minute
    hour = now.hour
    day = now.day
    month = now.month
    year = now.year

    timestring = "%04d-%02d-%02d %02d:%02d:%02d" % \
                 (year, month, day, hour, minute, second)
    print timestring

def setLocal(timestring, timezone = None):
    if timezone:
        os.environ['TZ'] = timezone
        time.tzset()

    os.system("date --set='%s'" % timestring)

def usage():
    print "Usage: timeutil getLocalTime [timezone]"
    print "    or timeutil setLocalTime <time> [timezone]"
    print
    print "<time> is YYYY-MM-DD HH:mm:SS"    
    
def main():
    if len(sys.argv) == 1:
        usage()
    else:
        if sys.argv[1] == 'getLocalTime':
            if len(sys.argv) == 3:
                getLocalNow(sys.argv[2])
            else:
                getLocalNow()
        elif sys.argv[1] == 'setLocalTime':
            if len(sys.argv) == 4:
                setLocal(sys.argv[2], sys.argv[3])
            else:
                setLocal(sys.argv[2])
        else:
            usage()

if __name__ == '__main__':
    main()
