//
//  TeXDistTool-main.m
//  TeXDistTool
//
//  Created by itexmac2 on 09/06/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "TeXDistCommon.h"

int TeXDistTool_activate(NSString * distributionName, NSString * architectureName);
int TeXDistTool_update(void);
int TeXDistTool_help(void);
int TeXDistTool_listDistributions(void);
int TeXDistTool_listActiveDistribution(void);
int TeXDistTool_reset(void);

int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSEnumerator * E = [NSProcessInfo processInfo].arguments.objectEnumerator;
	NSString * myPath = E.nextObject;
	NSString * path = myPath;
#   ifdef TeXDist_DEBUG
    path = myPath.stringByResolvingSymlinksInPath.stringByDeletingLastPathComponent;
    if (NOT [path.lastPathComponent isEqual:@"MacOS"]) {
        path = [path stringByAppendingPathComponent:@"TeXDistPrefPane.intel.prefPane"];
    } else {
        path = path.stringByDeletingLastPathComponent;
        if (NOT [path.lastPathComponent isEqual:@"Contents"]) {
            path = [path stringByAppendingPathComponent:@"TeXDistPrefPane.intel.prefPane"];
        } else {
            path = path.stringByDeletingLastPathComponent;
        }
    }
#   else
    path = path.stringByResolvingSymlinksInPath.stringByDeletingLastPathComponent;
    if (NOT [path.lastPathComponent isEqual:@"MacOS"]) {
        NSLog(@"Bad use");
        return 1;
    } else {
        path = path.stringByDeletingLastPathComponent;
        if (NOT [path.lastPathComponent isEqual:@"Contents"]) {
            NSLog(@"Bad use too");
        } else {
            path = path.stringByDeletingLastPathComponent;
        }
    }
#   endif
    NSBundle * B = [NSBundle bundleWithPath:path];
    NSError * ROR = nil;
    if (NOT [B preflightAndReturnError:&ROR]) {
        NSLog(@"preflightAndReturnError:%@",ROR);
        return -1;
    }
    if (NOT [B loadAndReturnError:&ROR]) {
        NSLog(@"loadAndReturnError:%@",ROR);
        return -2;
    }
    [NSClassFromString(@"TeXDistLoad") performSelector:@selector(setup)];
    NSString * argument = nil;
    int result = 0;
    while ((argument = E.nextObject)) {
        if ([argument isEqual:kTeXDistActivateArgument]) {
            NSString * sub_argument = nil;
            NSString * distributionName = nil;
            NSString * architectureName = nil;
            while ((sub_argument = E.nextObject)) {
                if ([sub_argument isEqual:kTeXDistributionArgument]) {
                    distributionName = E.nextObject;
                } else if ([sub_argument isEqual:kTeXDistArchitectureArgument]) {
                    architectureName = E.nextObject;
                }
            }
            result = TeXDistTool_activate(distributionName,architectureName);
        } else if ([argument isEqual:kTeXDistUpdateArgument]) {
            result = TeXDistTool_update();
        } else if ([argument isEqual:kTeXDistListDistributionsArgument]) {
            result = TeXDistTool_listDistributions();
        } else if ([argument isEqual:kTeXDistListActiveDistributionArgument]) {
            result = TeXDistTool_listActiveDistribution();
        } else if ([argument isEqual:kTeXDistHelpArgument]) {
            result = TeXDistTool_help();
        } else if ([argument isEqual:kTeXDistResetArgument]) {
            result = TeXDistTool_reset();
        } 
    }
    [pool drain];
    return result;
}
int TeXDistTool_activate(NSString * distributionName, NSString * architectureName)
{
    Class C = NSClassFromString(@"TeXDistController");
    id SC = [C performSelector:@selector(sharedController)];
    id D = [SC performSelector:@selector(distributionWithName:) withObject:distributionName];
    if (D) {
        id A = nil;
        if (architectureName.length) {
            if (NOT (A = [D performSelector:@selector(architectureWithName:) withObject:architectureName])) {
                NSLog(@"FAILURE: no architecture named %@",architectureName);
                return -1;
            }
        } else {
            if (NOT (A = [D valueForKey:@"preferredArchitecture"])) {
                NSLog(@"FAILURE: no preferred architecture.");
                return -1;
            }
        }
        [SC setValue:D forKey:@"activeDistribution"];
        //[D setValue:[NSNumber numberWithBool:YES] forKey:@"isActive"];
        if ([[SC valueForKey:@"activeDistribution"] isEqual:D]) {
            [D setValue:A forKey:@"activeArchitecture"];
            if ([[D valueForKey:@"activeArchitecture"] isEqual:A]) {
                NSLog(@"active distribution:\n%@",[D valueForKey:@"longDescription"]);
                return 0;
            }
            NSLog(@"FAILURE: cannot activate architecture named %@",[A valueForKey:@"name"]);
            return -1;
        }
        NSLog(@"FAILURE: cannot activate distribution named %@",distributionName);
        return -1;
    }
    NSLog(@"FAILURE: no distribution named %@",distributionName);
    return -1;
}
int TeXDistTool_reset(void)
{
    Class C = NSClassFromString(@"TeXDistController");
    id SC = [C performSelector:@selector(sharedController)];
    [SC performSelector:@selector(reset)];
    return 0;
}
int TeXDistTool_update(void)
{
    Class C = NSClassFromString(@"TeXDistController");
    id SC = [C performSelector:@selector(sharedController)];
    [SC performSelector:@selector(activeDistribution)];
    return 0;
}
int TeXDistTool_listDistributions(void)
{
    Class C = NSClassFromString(@"TeXDistController");
    id SC = [C performSelector:@selector(sharedController)];
    [SC performSelector:@selector(listDistributions)];
    return 0;
}
int TeXDistTool_listActiveDistribution(void)
{
    Class C = NSClassFromString(@"TeXDistController");
    id SC = [C performSelector:@selector(sharedController)];
    [SC performSelector:@selector(listActiveDistribution)];
    return 0;
}
int TeXDistTool_help(void)
{
    NSLog(@"TeXDistTool usage.\n"
@"In order to use the TeXDistTool, you must make a soft link:\n"
@"ln -s \"%@\" /SOMEWHERE/TeXDistTool\n"
@"Then you can call this tool to update the texdist context.\n"
@"    %%/SOMEWHERE/TeXDistTool %@\n"
@"This will list all the distributions available.\n"
@"    %%/SOMEWHERE/TeXDistTool %@\n"
@"This will list the active distribution.\n"
@"    %%/SOMEWHERE/TeXDistTool %@\n"
@"This will remove the /usr/texbin and .DefaultTeX soft links.\n"
@"All the commands below can be run in sudo mode.\n"
@"In that case, you can add the optional %@ argument to avoid subsequent credentials requests.\n"
@"    %%/SOMEWHERE/TeXDistTool %@ %@ %@ [%@ %@]\n"
@"This will make the distribution with the given name the active one.\n"
@"    %%/SOMEWHERE/TeXDistTool %@\n"
@"This will perform exactly the same tasks as the TeXDist preference pane\n"
@"when it loads in the preference application.",
[NSProcessInfo processInfo].arguments.objectEnumerator.nextObject,
kTeXDistListDistributionsArgument,kTeXDistListActiveDistributionArgument,kTeXDistResetArgument,
    kTeXDistNoCredentialsArgument,
kTeXDistActivateArgument,kTeXDistributionArgument,@"texlive-2011",kTeXDistArchitectureArgument,@"x86_64",
kTeXDistUpdateArgument
);
    return 0;
}
