#!/usr/bin/env swift

import Foundation

guard CommandLine.argc != 1 else {
	print("Require first param")
	exit(1)
}

let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
process.arguments = ["git", "symbolic-ref", "--short", "HEAD"]

var pipe = Pipe()

process.standardOutput = pipe
do{
  try process.run()
  let data = pipe.fileHandleForReading.readDataToEndOfFile()
  if let output = String(data: data, encoding: String.Encoding.utf8) {
      let branch = output.trimmingCharacters(in: .whitespacesAndNewlines)
	  exit(processCommitMessage(branch: branch,
                                filePath: CommandLine.arguments[1]))
  }
} catch {}

func processCommitMessage(branch: String, filePath: String) -> Int32 {
	
    let taskPrefix = "PSDK"
    let noissuePrefix = "noissue"
    let allowedRoot = ["feature", "release", "bugfix"]

    guard let commitMessage = try? String(contentsOfFile: filePath) else {
        print("Error. Can't read commit message file.")
        return 1
    }
	
    if commitMessage.hasPrefix("Merge") { return 0 }
    if commitMessage.hasPrefix(noissuePrefix) { return 0 }
    
    let branchComponents = branch.components(separatedBy: "/")
    let rootComponent = branchComponents[0]
    
    if branchComponents.count > 0, !allowedRoot.contains(rootComponent) {
        print("Error. Branch \(branch) require starts with one of \(allowedRoot)")
        return 1
    }

    guard let searchRegex = try? Regex("\(taskPrefix)-(\\d+) - (.*)") else {
        print("Error. Internal scripts.")
        return 1
    }
    
    guard let _ = try? searchRegex.firstMatch(in: commitMessage) else {
        print("Error. Incorrect commit message \"\(commitMessage)\" for branch \(branch)")
        return 1
    }
    
    if branchComponents.count > 1,
       !allowedRoot.contains(rootComponent) {
        print("Error. Invalid git path for branch \(branch)")
        return 1
    }
    
    guard let branchRegex = try? Regex("\(taskPrefix)-(\\d+)") else {
        print("Error. Internal scripts.")
        return 1
    }
    guard let branchMatch = try? branchRegex.firstMatch(in: commitMessage) else {
        print("Error. Incorrect commit message \(branch)")
        return 1
    }
    
    let branchPart = "\(commitMessage[branchMatch.range])"
    
    guard branchComponents.contains(branchPart) else {
        print("Error. Commit message \(branchPart) not correspond to branch \(branch)")
        return 1
    }
    
    return 0
}