"""
format devices

Formats a set of disks on a list of hosts

--prep: run swift drive prep before formatting the drives
--drive-file: file containing newline separated list of devices to format
hosts: list of hosts on which to format drives
"""

import requests
import sys
from multiprocessing import Pool
import threading
import argparse

def format_drives(args):
    """
    format drives takes a tuple containing three parameters, in the following order:

    host: host to format
    drive_file: file containing devices to format
    prep: run swift drive prep prior to formatting
    Drives are prepped sequentially but formatted in parallel.
    """

    host = args[0]
    drive_file = args[1]
    prep_it = args[2]

    def format(device):
        url = 'http://{0}.justin.tv:8082/format_device/{1}?fs=xfs'.format(host, device[:-1])
        print '[' + str(host) + '] ' + url
        resp = requests.post(url, proxies={'no': 'pass'})
        print '[' + str(host) + '] ' + resp.text

    def prep(device):
        url = 'http://{0}.justin.tv:8082/prep_device/'.format(host) + device[:-1]
        print '[' + str(host) + '] ' + url
        resp = requests.post(url, proxies={'no': 'pass'})
        print '[' + str(host) + '] ' + resp.text

    with open(drive_file, 'r') as f:
        threads = []
        for device in f:
            if prep_it:
                prep(device)
            t = threading.Thread(target=format, args=(device, ))
            t.daemon = True
            t.start()
            threads.append(t)
        for t in threads:
            t.join()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Tool to format drives on different boxes')
    parser.add_argument('--prep', action='store_true', help='Run swift drive prep before formatting')
    parser.add_argument('--drive-file', type=str, required=True, help='File with drive names separated by newlines')
    parser.add_argument('hosts', type=str, nargs='+', help='Hosts to format drives on')
    args = parser.parse_args()

    p = Pool(16)

    p.map(format_drives, [(host, args.drive_file, args.prep) for host in args.hosts])
