#!/usr/bin/env ruby

require 'pry'
require 'pathname'
require 'optparse'
require 'active_support'
require 'active_support/core_ext/hash'
require 'open3'

@SCRIPT = Pathname.new(__FILE__).expand_path
@SCRIPTDIR = @SCRIPT.dirname
@MADEK_ROOT_DIR = @SCRIPTDIR + ".."

SUBS = [
  ["admin-webapp", "datalayer"],
  ["api", "datalayer"],
  ["webapp", "datalayer"],
]

@refs = {}

@opts = {"super-ref": "origin/master"}.with_indifferent_access

OptionParser.new do |parser|

  parser.banner = "madek-update-and-commit-datalayer-submodules resets super project to SUPER-REF and commits all datalayer submodules relative to that"

  parser.on("-c", "--commit-id COMMIT-ID", "COMMIT-ID to set datalayer modules to")
  parser.on("-s", "--super-ref SUPER-REF", "set the madek super project to SUPER-REF, default #{@opts['super-ref']}")
  parser.on("-m", "--commit-message COMMIT-MESSAGE", "the COMMIT-MESSAGE used in the super and ervery service ")
  parser.on("-b", "--branch-name BRANCH-NAME", "set local BRANCH-NAME and also push it")

  parser.on("-h", "--help", "Print help") do
    puts parser
    exit 0
  end

end.parse!(into: @opts)

raise "COMMIT-ID is required" unless @opts["commit-id"].present?
raise "COMMIT-MESSAGE is required" unless @opts["commit-message"].present?
raise "BRANCH-NAME is required" unless @opts["branch-name"].present?

puts @opts

puts @SCRIPT, @SCRIPTDIR, @MADEK_ROOT_DIR

def exec_shell_command(cmd, fail_on_error=true)
  puts '#######################################################################'
  puts "# in #{Dir.pwd}"
  puts "# #{cmd}"
  stdout, stderr, status = Open3.capture3(cmd)
  puts '#######################################################################'
  puts "\n\n"
  if fail_on_error and status.exitstatus != 0
    raise "cmd #{Shellwords.escape(cmd)} exited with #{status.exitstatus} : #{stderr}"
  end
  return stdout
end

Dir.chdir @MADEK_ROOT_DIR do

  exec_shell_command "git fetch --all --recurse-submodules"
  exec_shell_command "git checkout --force #{@opts['super-ref']}"
  exec_shell_command "git submodule update --init --recursive --force"

  SUBS.each do |submodule, db_path|
    Dir.chdir submodule do
      Dir.chdir db_path do
        exec_shell_command "git reset --hard #{@opts['commit-id']}"
      end
      exec_shell_command "git add #{db_path}"

      exec_shell_command "git commit --allow-empty -m #{Shellwords.escape(@opts['commit-message'])}"

      @refs[submodule] = exec_shell_command('git rev-parse HEAD').strip
    end

    exec_shell_command "git add #{submodule}"
  end

  exec_shell_command "git commit -m #{Shellwords.escape(@opts['commit-message'])}"

  # set branches and push
  escaped_branch_name = Shellwords.escape(@opts['branch-name'])
  SUBS.push([".", nil]).each do |submodule, db_path|
    Dir.chdir submodule do
      exec_shell_command "git switch -C #{escaped_branch_name}"
      exec_shell_command "git push -f -u origin #{escaped_branch_name}:#{escaped_branch_name}"
    end
  end
end
