#!/usr/bin/python3
#
# Copyright (C) Citrix Systems Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation; version 2.1 only.
#
# 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser 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
#
# Clear the attach status for all VDIs in the given SR on this host.
# Additionally, reset the paused state if this host is the master.
import sys
import atexit

import XenAPI # pylint: disable=import-error
from sm import resetvdis

def usage():
    print("Usage:")
    print("all <HOST UUID> <SR UUID> [--master]")
    print("single <VDI UUID> [--force]")
    print()
    print("*WARNING!* calling with 'all' on an attached SR, or using " + \
            "--force may cause DATA CORRUPTION if the VDI is still " + \
            "attached somewhere. Always manually double-check that " + \
            "the VDI is not in use before running this script.")
    sys.exit(1)

if __name__ == '__main__':
    if len(sys.argv) not in [3, 4, 5]:
        usage()

    session = XenAPI.xapi_local()
    session.xenapi.login_with_password('root', '', '', 'SM')
    atexit.register(session.xenapi.session.logout)

    mode = sys.argv[1]
    if mode == "all":
        if len(sys.argv) not in [4, 5]:
            usage()
        host_uuid = sys.argv[2]
        sr_uuid = sys.argv[3]
        is_master = False
        if len(sys.argv) == 5:
            if sys.argv[4] == "--master":
                is_master = True
            else:
                usage()
        resetvdis.reset_sr(session, host_uuid, sr_uuid, is_master)
    elif mode == "single":
        vdi_uuid = sys.argv[2]
        force = False
        if len(sys.argv) == 4 and sys.argv[3] == "--force":
            force = True
        resetvdis.reset_vdi(session, vdi_uuid, force)
    elif len(sys.argv) in [3, 4]:
        # backwards compatibility: the arguments for the "all" case used to be
        # just host_uuid, sr_uuid, [is_master] (i.e., no "all" string, since it
        # was the only mode available). To avoid having to change XAPI, accept
        # the old format here as well.
        host_uuid = sys.argv[1]
        sr_uuid = sys.argv[2]
        is_master = False
        if len(sys.argv) == 4:
            if sys.argv[3] == "--master":
                is_master = True
            else:
                usage()
        resetvdis.reset_sr(session, host_uuid, sr_uuid, is_master)
    else:
        usage()
