#! /usr/bin/env ruby
# frozen_string_literal: true

require 'fileutils'

require 'flood/configuration'
require 'flood/utils'

def usage
  puts 'flood-init [config|systemd]'
  puts "\nRun as root if you want to set it up globally"
  exit false
end

def copy_template(target_dir)
  unless Dir.exist? target_dir
    print "[..] Creating config dir at #{target_dir} ..."
    FileUtils.mkdir_p target_dir
    puts 'OK'
  end
  unless Dir.exist? File.join(target_dir, 'config_template.yaml')
    print '[..] Copying template configuration ... '
    FileUtils.cp InitPaths::TEMPLATE_PATH, target_dir
    puts 'OK'
  end
  puts '[**] Done'
end

def init_systemd(target_dir)
  print "[..] Creating systemd config dir at '#{target_dir}' ... "
  FileUtils.mkdir_p target_dir
  puts 'OK'
  print '[..] Preparing service and timer files ... '
  FileUtils.cp InitPaths::TIMER_PATH, target_dir
  setup_service_file target_dir
  puts 'OK'
  puts '[**] Done'
  puts '[ii] If desired you can now enable and start the timer with \'systemctl (--user) enable --now flood-backup.timer\''
  puts '[ii] The timer is currently set to start all backup jobs at 12:00 every day'
end

def setup_service_file(target_dir)
  exec_path = `which flood`.strip
  contents = File.read(InitPaths::SERVICE_PATH).sub(/<exec-path>/, exec_path)
  File.write(File.join(target_dir, 'flood-backup.service'), contents)
end

usage if ARGV.empty?

if root_user?
  config_dir = Configuration::CONF_DIR_SYSTEM
  systemd_dir = InitPaths::SYSTEMD_TARGET_DIR_SYSTEM
else
  config_dir = Configuration::CONF_DIR_USER
  systemd_dir = InitPaths::SYSTEMD_TARGET_DIR_USER
end

ARGV.each do |arg|
  case arg
  when 'config'
    copy_template config_dir
  when 'systemd'
    init_systemd systemd_dir
  else
    puts "[!!] Unknown argument '#{arg}'"
  end
rescue StandardError => e
  puts 'ERROR'
  puts "[!!] Something went wrong: #{e}"
end
