#!/usr/bin/python3
# kate: space-indent on; indent-width 4; replace-tabs on; indent-mode python; remove-trailing-space modified;
# vim: expandtab ts=4

############################################################################
#   Copyright © 2015 José Manuel Santamaría Lema <panfaust@gmail.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; either version 2 of the License, or      #
#   (at your option) any later version.                                    #
############################################################################

import os
import sys
import subprocess

from lib.utils import *

root, dirs, files = next(os.walk('.'))
old_cwd = os.getcwd()

command_index = 1
r_option = False

if len(sys.argv) == 1:
    print("usage: do-all [-r <release_type>] <command>")
    print("the above would execute 'command' in all the subdirectories of the current directory")
    print("(or only in the ones belonging to 'release_type')")
    print("'release_type' is either 'frameworks', 'plasma' or 'applications'")
    sys.exit(1)
else:
    if sys.argv[1] == "-r":
        command_index = 3
        version_map = getFtpVersionMap(sys.argv[2])
        dirs = version_map.keys()
    else:
        command_index = 1

command = " ".join(sys.argv[command_index:])

dirs_failed = []
dirs_not_accessible = []
dirs_ignored = []

skip_list = readConfigFile("skip.json")["do-all"]

#Execute the command in all directories
i = 0
n = len(dirs)
for directory in dirs:
    i += 1
    print("----------------------------------------------------------------------")
    print("do-all current directory: %s (%s of %s)" % (directory,i,n))
    print("----------------------------------------------------------------------")
    try:
        os.chdir(old_cwd + '/' + directory)
    except:
        dirs_not_accessible.append(directory)
        print("directory not accessible, failed to 'cd' into it")
    if directory in skip_list:
        print("As requested by the conf/skip.json configuration file,\n"
            "the command wasn't executed in this directory")
        dirs_ignored.append(directory)
        continue
    try:
        returncode = subprocess.call(command,shell=True)
    except KeyboardInterrupt:
        print("abort by user request")
        sys.exit(130)
    if returncode != 0:
        dirs_failed.append((directory,returncode))

#Print summary
print("----------------------------------------------------------------------")
print("Summary:")
if not dirs_failed:
    print("The command was executed sucessfully in all the directories.")
else:
    print("The command failed to execute in the following directories:")
    for d in dirs_failed:
            directory, retcode = d
            print(directory + " (exit status = " + str(retcode) + ")")
if dirs_ignored:
    print("As requested by the conf/skip.json configuration file,\n"
        "the command wasn't executed in the following directories:")
    print(dirs_ignored)
if dirs_not_accessible:
    print("The command was skipped for the following non accesible directories:")
    print(dirs_not_accessible)
print("----------------------------------------------------------------------")
