/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 2013. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/
import com.urbancode.air.AirPluginTool;

final def airTool = new AirPluginTool(args[0], args[1])
final def props = airTool.getStepProperties()


def final fstabPath = props['fstabPath']
def final ruleSet = props['ruleSet']?:''
def final removeSet = props['removeSet']?:''
def final backupSuffix = props['backupSuffix']
def final owner = props['owner']
def final permissions = props['permissions']
def final tmpFile = File.createTempFile('fstab', '.tmp')
def foundError = false

println "fstabPath: $fstabPath"
println "Add/Update rules: $ruleSet"
println "Remove rules: $removeSet"
println "Backup Suffix: $backupSuffix"
println "File owner: $owner"
println "File permissions: $permissions"
println ""

def fstabFile = new File('/etc/fstab')
if (fstabPath && fstabPath.trim().length() > 0) {
    fstabFile = new File(fstabPath)
}

if (fstabFile.isDirectory()) {
    println "fstab file path $fstabPath points to a directory!"
    System.exit 1
}


try {
    def rules = [:] as Map
    def removeRules = [] as Set
    ruleSet.split('[\r\n]').each {
        if (it && it.trim().length() > 0) {
            rules[it.trim().split('[ \t]')[0].trim()] = it.trim()
        }
    }
    removeSet.split('[\r\n]').each {
        if (it && it.trim().length() > 0) {
            removeRules << it.trim()
        }
    }

    if (rules.size() == 0 && removeRules.size() == 0) {
        println 'No rules specified, nothing to do!'
    }
    else {
        tmpFile.withOutputStream { out ->
            fstabFile.eachLine{ line ->
                if (line) {
                    dev = line.trim().split('[ \t]')[0].trim()
                    if (removeRules.contains(dev)) {
                        // do nothing
                        println "removing: \'$dev\'"

                    }
                    else if (rules.containsKey(dev)) {
                        out << rules[dev] + '\n'
                        rules.remove(dev)
                        println "updating: \'$dev\'"
                    }
                    else {
                        out << line + '\n'
                        if (!dev.startsWith("#")) {
                            println "preserving: \'$dev\'"
                        }
                    }
                }
            }

            for(rule in rules.values()) {
                out << rule + '\n'
            }

            out.flush()
        }

        def ant = new AntBuilder()
        if (backupSuffix && backupSuffix.trim().length() > 0) {
            ant.move(file: fstabFile, tofile: fstabFile.toString() + backupSuffix, overwrite: 'true', verbose: 'true')
        }
        ant.move(file: tmpFile, tofile: fstabFile, overwrite: 'true', verbose: 'true')
        if (owner && owner.trim().length() > 0) {
            ant.chown(file: fstabFile, 'owner': owner.trim(), verbose: 'true')
        }
        if (permissions && permissions.trim().length() > 0) {
            ant.chmod(file: fstabFile, perm: permissions.trim(), verbose: 'true')
        }
    }

}
catch (Exception e) {
    println e.message
    foundError = true
}
finally {
    if (tmpFile.exists()) {
        tmpFile.delete()
    }
}

if (foundError) {
    System.exit 1
}
else {
    System.exit 0
}
