#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# The Qubes OS Project, http://www.qubes-os.org
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#
#
import sys
from qubes.qubes import QubesVmCollection

def main():
    if len(sys.argv) != 4:
        print >> sys.stderr, \
            'Usage: qvm-appmenu-replace VM_NAME OLD_NAME.desktop NEW_NAME.desktop'
        sys.exit(1)
    vm_name = sys.argv[1]
    old_name = sys.argv[2]
    new_name = sys.argv[3]

    qvm_collection = QubesVmCollection()
    qvm_collection.lock_db_for_reading()
    qvm_collection.load()
    qvm_collection.unlock_db()

    vm = qvm_collection.get_vm_by_name(vm_name)

    if vm is None:
        print >> sys.stderr, "ERROR: A VM with the name '{0}' " \
                             "does not exist in the system.".format(
                                 vm_name)
        exit(1)

    if vm.template is not None:
        print >> sys.stderr, "ERROR: To replace appmenu for template based VM, " \
                             "do it on template instead"
        exit(1)

    vm.appmenus_replace_entry(old_name, new_name)
    if hasattr(vm, 'appvms'):
        for child_vm in vm.appvms.values():
            child_vm.appmenus_replace_entry(old_name, new_name)

main()
