import org.ini4j.Wini

final def workDir = new File('.').canonicalFile
final def props = new Properties();
final def inputPropsFile = new File(args[0]);
try {
    inputPropsStream = new FileInputStream(inputPropsFile);
    props.load(inputPropsStream);
}
catch (IOException e) {
    throw new RuntimeException(e);
}

final def fileName = props['file']
final def add = props['add']
final def remove = props['remove']

def file = new File(fileName)
if (!file.exists()) file.createNewFile()

def ini = new Wini(file)
try {
    println "Updating file $file"
    add?.eachLine {
        if (it && it.trim().length() > 0 && it.indexOf('=') > -1) {
            def index = it.indexOf('=')
            def group
            def name = it.substring(0, index)
            def value = ''
            if (index < it.length() - 1) {
                value = it.substring(index + 1)
            }

            if (name.lastIndexOf('\\') != -1) {
                group = name.substring(0, name.lastIndexOf('\\'))
                name = name.substring(name.lastIndexOf('\\') + 1)
            }
            println "Setting $it"
            if (!group) throw new Exception("Could not detect group name in $it")

            ini.put(group, name, value)
        }
    }
    remove?.eachLine {
        if (it && it.trim().length() > 0) {
            println "Removing $it"
            def group
            def name = it
            if (name.lastIndexOf('\\') != -1) {
                group = name.substring(0, name.lastIndexOf('\\'))
                name = name.substring(name.lastIndexOf('\\') + 1)
            }

            if (!group) throw new Exception("Could not detect group name in $it")

            try {
                ini.get(group).remove(name)
            }
            catch (Exception ee) {
                // this is to prevent failing on non-existent values
            }
        }
    }
    ini.store()
}
catch (Exception e) {
    println "Error updating file $file: ${e.message}"
    System.exit(1)
}

System.exit(0)

