#!/usr/bin/env ruby

# Required modules from Ruby Std-Lib (not gems)
require 'fileutils' # For mkdir_p, cp, mv

if ARGV.length < 1
  puts
  puts "Usage: ratmyrepo.rb '<description>'"
  puts "(Run this from the repo dir!)"
  puts
  exit 1
end

repo_dir = Dir.pwd
description = ARGV[0]

repo_name = File.basename(repo_dir)

puts "Rattin' up repo '#{repo_name}'"
puts "  Source: '#{repo_dir}'"
puts "  Description: '#{description}'"

# The relative git repo (probably in proj/ directory)
git_dir = "#{repo_dir}/.git"
git_desc_path = "#{git_dir}/description"

if !Dir.exist?(git_dir)
  puts "ERROR: Could not find #{git_dir}."
  exit 1
end

# Write repo description
puts "  Writing description to #{git_desc_path}..."
File.write(git_desc_path, description)
wrote_desc = File.read(git_desc_path)
if wrote_desc == description
  puts "  (Write verified!)"
else
  puts "ERROR: Written description, '#{wrote_desc}' does not match!"
  puts "       Check #{git_desc_path}?"
  exit 1
end

# Create bare repo
bare_dir = "#{ENV['HOME']}/repos/#{repo_name}.git"

puts "Time to create bare Git repo at '#{bare_dir}'..."
if !Dir.exist?(bare_dir)
  answer = nil
  until answer == 'y' or answer == 'n'
    print "Proceed? (y/n) "
    answer = $stdin.gets.chomp
  end
  if answer == 'y'
    # Create dir(s)! mkdir_p creates subdirs as needed
    puts "Creating '#{bare_dir}'..."
    FileUtils.mkdir_p(bare_dir)
    # No need to print anything here since Git says what it's doing:
    `git clone --bare #{repo_dir} #{bare_dir}`
  else
    puts "Okay, exiting!"
    exit 1
  end
else
  puts "ERROR: Bare dir already exists! Have you done this before?"
  exit 1
end

puts "Bare repo created at '#{bare_dir}'. Listing:"
puts ""
system "ls -al #{bare_dir}"
puts ""

# Add comment to git config and have myself edit file manually...
git_config_path = "#{git_dir}/config"
origin_block = "
#[remote \"origin\"]
#    url = #{bare_dir}
#    fetch = +refs/heads/*:refs/remotes/origin/*
#[branch \"main\"]
#    remote = origin
#    merge = refs/heads/main
"
File.write(git_config_path, origin_block, mode: 'a')
puts "Wrote a replacement 'origin' block as a comment to '#{git_config_path}'."
puts "Hit [Enter] to edit the file to use the new origin."
$stdin.gets # waits for line of input
system "#{ENV['EDITOR']} #{git_config_path}"

# That should do it
puts "All done:"
puts
puts "  * Description added."
puts "  * Bare repo created."
puts "  * Repo origin updated."
puts
puts "Things to try next:"
puts
puts "  * cd #{repo_dir}"
puts "  * git push"
puts "  * git pull"
puts "  * reporat"
puts "  * or reporat && rat pub"
puts
puts "Enjoy!"
