#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# vim: set ts=2 sw=2 sts=2 et:

# ansible-inventory. An Inventory Manager for Ansible
# Copyright (C) 2016  Diego Blanco <diego.blanco@treitos.com>
#
# 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, version 3 of the License.
#
# 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, see <http://www.gnu.org/licenses/>.


# ( IMPORTS
import argparse
import os
import sys
from ansible_inventory import AnsibleInventory
from ansible_inventory.backends import AnsibleInventory_FileBackend as AI_FileBackend
from ansible_inventory.config import AnsibleInventory_Config as AI_Config
from ansible_inventory.frontends import AnsibleInventory_Console as AI_Console
# )

# ( CONFIG
# )

# ( CLASSES

# )

if __name__ == '__main__':
  # Parse command line arguments
  parser = argparse.ArgumentParser( description='Ansible Inventory manager' )
  group = parser.add_mutually_exclusive_group()
  group.add_argument('--import', dest='inventory', action='store',
                      help='Import an existing ansible inventory. It must be in the ansible dynamic inventory JSON format.')
  group.add_argument('--batch', dest='command', action='store',
                     help='Execute an Ansible Inventory command in batch mode. (i.e. "add host test host=1.2.3.4" ).')
  group.add_argument('--list', dest='list', action='store_true',
                     help='Used by Ansible. Dumps the current inventory.')
  group.add_argument('--host', dest='host', action='store',
                     help='Used by Ansible. Dumps the inventory information of a known host.')
  args = parser.parse_args()

  # Get configuration
  config = AI_Config(__file__)

  # Import
  if args.inventory:
    print(" This will overwrite the current inventory. Are you sure you want to continue? [N/y]: ", end="")
    sys.stdout.flush()
    ans = sys.stdin.readline()
    if ans.replace('\n', '').lower() in ('y', 'yes'):
      json_file_import = args.inventory
      if not os.path.exists( json_file_import ):
        print("File %s does not exist." % json_file_import)
        sys.exit( 1 )
    else:
      sys.exit( 1 )

    inventory = AnsibleInventory(
      AI_FileBackend( { "path": os.path.abspath(json_file_import) }, config )
    )
    inventory.backend = config.backend['class']( config.backend['parameters'], config)
    inventory.save()
    sys.exit( 0 )

  # Load inventory and create console
  inventory = AnsibleInventory(
    config.backend['class']( config.backend['parameters'], config )
  )
  console = AI_Console( inventory, config )

  # Import
  if args.command:
    config.use_colors = False
    cmd = args.command
    console.onecmd( cmd )
    sys.exit( 0 )

  # Ansible requests
  if args.list:
    print( inventory.get_ansible_json() )
    sys.exit( 0 )

  if args.host:
    host = args.host
    print( inventory.get_ansible_host_json(host) )
    sys.exit( 0 )

  # Main console loop
  console.cmdloop()
