#!/usr/bin/env python

import sys
import argparse
import sqlite3


def add_devices(cursor, device_list):
    query = 'insert into ZDEVICE (ZNAME) values (?)'

    for device in device_list:
        print "Adding", device
        try:
            cursor.execute(query, (device,))
        except sqlite3.Error, e:
            print "add_devices:", e.args[0]
            return 1
            
    return 0

def process_arguments(argv=None):
    if argv is None:
        argv = sys.argv[1:]
    
    parser = argparse.ArgumentParser()
    parser.add_argument('mps_file_path', metavar='MPS_LOGIC_FILE', help='.mpl file')
    parser.add_argument('device_list_file_path', metavar='NEW_DEVICE_LIST', help='new device list')
    parser.add_argument('-n', '--dry-run', action='store_true', help='show patch actions without actually applying them')
    args = parser.parse_args(argv)
    
    return args


def main(argv=None):
    if argv is None:
        argv = sys.argv[1:]
 
    args = process_arguments(argv)
    
    device_list = []
    with open(args.device_list_file_path) as f:
        for line in f:
            line = line.strip()
            if line:
                device_list.append(line)
    
    
    connection = sqlite3.connect(args.mps_file_path)
    connection.row_factory = sqlite3.Row
    cursor = connection.cursor()
    
    status = add_devices(cursor, device_list)
    
    if args.dry_run:
        connection.rollback()
        print '** Dry Run.  Devices not added. **'
    else:
        connection.commit()
        
    connection.close()
    
    return status

if __name__ == '__main__':
    status = main()
    sys.exit(status)
    
    