#!/usr/bin/python -W ignore
import sys
import os
import socket
import ConfigParser
import urllib3
import time

# this is a hack to get the hpe driver module
# and it's utils module on the search path.
cmd_folder = os.path.realpath(os.path.abspath("..") )
if cmd_folder not in sys.path:
     sys.path.insert(0, cmd_folder)

from hpe3parclient import client, exceptions
import common

sys.path.append("/usr/share/ganeti/default")
from ganeti import utils


def main():
  sys.stderr.write('Detach started...\n')

  (host,login,password,default_cpg,snap_cpg) = common.getConfig()
  (vol_name,vol_cname,vol_size,vol_new_size,vol_uuid,vol_metadata,vol_snapshot_name,vol_snapshot_size,vol_open_exclusive,cpg) = common.readEnv()

  sys.stderr.write('cname: %s\n' % (vol_cname))

  cl = client.HPE3ParClient(host, False, False, None, True)

  try: 
    cl.login(login,password)
  except exceptions.HTTPUnauthorized as ex:
       pprint.pprint("Login Failed")
  
  try:
    vlun = cl.getVLUN(vol_cname)
    export_host = socket.gethostname()
    cl.deleteVLUN(vol_cname,vlun['lun'],export_host,None)

    time.sleep(3)
    result = utils.RunCmd('multipath -F')
    cmd="for i in `pvs 2>&1 | grep 'read failed' | awk '{print $1}' | sed 's/://' | sed 's/\/dev\///' | uniq` ; do echo 1> /sys/block/$i/device/delete; done"
    result = utils.RunCmd(cmd)

  except exceptions.HTTPUnauthorized as ex: 
       pprint.pprint("You must login first")
  except Exception as ex:
       print(ex)

  cl.logout()


if __name__ == "__main__":
  sys.exit(main())

