#!/usr/bin/env python3

import argparse
import subprocess
import json
import datetime
import os

import concurrent.futures

orgname = 'university-of-colorado-boulder'

parser = argparse.ArgumentParser()
parser.add_argument("--create-site", help="Deploy a new site", nargs='+')
parser.add_argument("--delete-site", help="Delete an existing site")
parser.add_argument("--list-sites", help="List existing sites", action='store_true')
parser.add_argument("--drush", help="Execute a drush command against a site", nargs='+')
parser.add_argument("--get-backup-info", help="Fetch information about a site's backups")
parser.add_argument("--parallel", help="Execute operations in parallel", action='store_true')
args = parser.parse_args()


def list_sites():
  print("Fetching site list...")

  sitelist = json.loads(
    subprocess.run("terminus site:list --format=json", shell=True, capture_output=True).stdout.decode('utf-8'))
  for key in sitelist:
    site = sitelist[key]
    if site['framework'] != 'drupal8':
      continue
    print(site['name'])


def delete_site(arg1):
  print("Deleting site...")
  subprocess.run("terminus site:delete " + arg1, shell=True)


def create_site(arg1):
  sitename = arg1

  print("Creating site '" + arg1 + "'...")
  subprocess.run('terminus site:create --org="university-of-colorado-boulder" --  ' + sitename + ' ' + sitename + ' "Private Experimental Upstream"', shell=True, executable='/bin/bash')

  print("Installing drupal on " + arg1 + "...")
  subprocess.run('terminus drush ' + arg1 + '.dev -- site-install ucb2021_profile -y', shell=True)

  print('Done!')

def get_backup_info(arg1):
  result = subprocess.run(['terminus', 'backup:list', args.get_backup_info, '--format=json'], capture_output=True)
  backupinfo = json.loads(result.stdout)
  for b in backupinfo:
    parts = backupinfo[b]['file'].split("_")
    site = parts[0]
    env = parts[1]
    timestamp = parts[2]
    tz = parts[3]
    type = parts[4].split('.')[0]
    print("Site: " + site + ", Env: " + env + ", Type: " + type + ", Timestamp: " + timestamp)
    # print(backupinfo[b]['file'].split("_")[0])
    # print(backupinfo[b]['file'].split("_")[1])
    # print(backupinfo[b]['file'].split("_")[2])
    # print(backupinfo[b]['file'].split("_")[3])
    # print(backupinfo[b]['file'].split("_")[4].split('.')[0])

def execute_drush(envname, command):
  subprocess.run('terminus remote:drush ' + envname + ' ' + command, shell=True)


if args.list_sites:
  list_sites()

if args.delete_site:
  delete_site(args.delete_site)

if args.create_site:
  if args.parallel:
    with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
      for _ in executor.map(create_site, args.create_site):
        pass

  else:
    for site in args.create_site:
      print(site)
      create_site(site)

if (args.get_backup_info):
  get_backup_info(args.get_backup_info)

if args.drush:
  execute_drush(args.drush[0], args.drush[1])



