package org.gnu.grub.fonttool;

import java.io.IOException;

/**
 * Program to convert BDF fonts into PFF2 fonts for use with GRUB.
 */
public class Converter {
    public static void main(String[] args) {
        if (args.length < 1) {
            printUsageAndExit();
        }

        String in = null;
        String out = null;

        try {
            for (String arg : args) {
                if (arg.startsWith("--")) {
                    String option;
                    String value;
                    int equalsPos = arg.indexOf('=');
                    if (equalsPos < 0) {
                        option = arg.substring(2);
                        value = null;
                    } else {
                        option = arg.substring(2, equalsPos);
                        value = arg.substring(equalsPos + 1);
                    }

                    if ("in".equals(option)) {
                        if (value == null)
                            throw new CommandLineException(option + " option requires a value.");
                        in = value;
                    } else if ("out".equals(option)) {
                        if (value == null)
                            throw new CommandLineException(option + " option requires a value.");
                        out = value;
                    }
                } else {
                    throw new CommandLineException("Non-option argument `" + arg + "'.");
                }
            }
            if (in == null || out == null) {
                throw new CommandLineException("Both --in=X and --out=Y must be specified.");
            }
        } catch (CommandLineException e) {
            System.err.println("Error: " + e.getMessage());
            System.exit(1);
        }

        try {
            // Read BDF.
            Font font = BDFLoader.loadFontFile(in);

            // Write PFF2.
            new PFF2Writer(out).writeFont(font);
        } catch (IOException e) {
            System.err.println("I/O error converting font: " + e);
            e.printStackTrace();
            System.exit(1);
        }
    }

    private static class CommandLineException extends Exception {
        public CommandLineException(String message) {
            super(message);
        }
    }

    private static void printUsageAndExit() {
        System.err.println("GNU GRUB Font Conversion Tool");
        System.err.println();
        System.err.println("Usage: Converter --in=IN.bdf --out=OUT.pf2");
        System.err.println();
        System.exit(1);
    }
}
