#! /usr/bin/env python
########################################################################
# COPYRIGHT_BEGIN
#
#           mical
#           Minimal iCalendar utilities
#
# Copyright (C) 2007, David Arnold
# 
# 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., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# COPYRIGHT_END
########################################################################
# $ZeroXOne: mical/micsave,v 1.4 2007/06/06 00:48:10 d Exp $
########################################################################

import sys, os

########################################################################

def usage(msg=None):
    if msg:
        print msg
    print "Usage: %s id action" % os.path.basename(sys.argv[0])
    return


def main():

    # Read stdin
    raw_text = sys.stdin.read()

    # Find last id
    try:
        f = open("%s/.mical/last" % os.environ["HOME"])
        last = int(f.read().strip())
        f.close()
    except IOError:
        usage("mical not initialized.  Please run micsetup")
        sys.exit(1)

    # Write this event
    this = last + 1
    try:
        f = open("%s/.mical/%d" % (os.environ["HOME"], this), "w")
        f.write(raw_text)
        f.close()
    except:
        usage("failed to write event")
        sys.exit(1)

    # Update last id
    try:
        f = open("%s/.mical/last" % os.environ["HOME"], "w")
        f.write(str(this))
        f.close()
    except OSError:
        usage("failed to update event id")
        os.remove("%s/.mical/%d" % (os.environ["HOME"], this))
        sys.exit(1)

    # Print id of message saved
    print this
    sys.exit(0)

if __name__ == "__main__":
    main()

########################################################################
