/*
 * Copyright 2023 Canonical Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.debian.javatools;

/**
 * Check the value of a system property from the command line.
 *
 * Syntax:
 *
 *   java org.debian.javatools.CheckIntProperty <propertyName> <condition> <expectedValue>
 *
 *   <condition>:
 *          - gte - greater or equal
 *          - lte - less than or equal
 *          - gt  - greater than
 *          - lt  - less than
 *
 * The program exits with the status code 0 if the condition is true, and 1 otherwise.
 */
public class CheckIntProperty {

    private static boolean check(String operation, int actualValue, int expectedValue){
        switch (operation) {
            case "gt": return actualValue > expectedValue;
            case "gte": return actualValue >= expectedValue;
            case "lte": return actualValue <= expectedValue;
            case "lt": return actualValue < expectedValue;
            default: return false;
        }
    }

    private static boolean isVerbose() {
        try {
            return Integer.parseInt(System.getenv("DH_VERBOSE")) != 0;
        } 
        catch (NumberFormatException ex) {
            // ignored
        }
        return false;
    }

    public static void main(String[] args) {
        boolean verbose = isVerbose();
        String propertyName = args[0];
        String operation = args[1];
        try {
            int expectedValue = Integer.parseInt(args[2]);
            int actualValue = Integer.parseInt(System.getProperty(propertyName));
            if (check(operation, actualValue, expectedValue)) {
                if (isVerbose())
                    System.out.println("OK: " + propertyName + " " + actualValue + " " + operation + " " + expectedValue);
                System.exit(0);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        if (isVerbose()) {
            System.out.println("FAILED: " + propertyName + " " + System.getProperty(propertyName) + " " + operation + " " + args[2]);
        }
        System.exit(1);
    }
}
