/**
 * Adapted from https://proandroiddev.com/ooga-chaka-git-hooks-to-enforce-code-quality-11ce8d0d23cb
 */

static def isLinuxOrMacOs() {
    def osName = System.getProperty('os.name').toLowerCase(Locale.ROOT)
    return osName.contains('linux') || osName.contains('mac os') || osName.contains('macos')
}

task copyGitHooks(type: Copy) {
    description 'Copies the git hooks from scripts/git-hooks to the .git folder.'
    from("${rootDir}/scripts/git-hooks/") {
        include '**/*.sh'
        rename '(.*).sh', '$1'
    }
    into "${rootDir}/.git/hooks"
    onlyIf { isLinuxOrMacOs() }
}

task installGitHooks(type: Exec) {
    description 'Installs the git hooks from scripts/git-hooks.'
    group 'git hooks'
    workingDir rootDir
    commandLine 'chmod'
    args '-R', '+x', '.git/hooks/'
    dependsOn copyGitHooks
    onlyIf { isLinuxOrMacOs() }
    doLast {
        logger.info('Git hooks installed successfully.')
    }
}

afterEvaluate {
    // We install the hook at the first occasion
    tasks['clean'].dependsOn installGitHooks
}
