#!/usr/bin/python

# Copyright (C) 2009 by Magnus Therning

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import sys
sys.path = ['/usr/lib/keysafe'] + sys.path

from optparse import OptionParser, make_option
import getpass

import libkeysafe.oldsafe as oldsafe
import libkeysafe.safe as safe

_OPTIONS = [ \
        make_option('-s', '--safe', help='keysafe store (old format)'), \
        make_option('-o', '--filename', \
            help='filename for the new keysafe (new format)'), \
        ]

def main():
    parser = OptionParser(option_list=_OPTIONS)
    options, args = parser.parse_args()
    master_pwd = getpass.getpass()

    outfile = sys.stdout

    ocfg = {'keyfile' : options.safe}
    ncfg = {'keyfile' : options.filename}
    os = oldsafe.get_safe(config=ocfg)
    ns = safe.get_safe(config=ncfg)
    for k in os.keys():
        un = os[k][0]
        pw = oldsafe.decrypt(os[k][1], master_pwd)
        text = os[k][2]
        safe.set_entry(k, un, pw, text, master_pwd)
    
    safe.save_safe(config=ncfg)

if __name__ == '__main__':
    main()
