#!/usr/bin/env ruby
# frozen_string_literal: true
#
# Sets (or resets) the single ValidBoard password.
#
#   bin/validboard-passwd                 # prompts, twice, without echo
#   VALIDBOARD_DB=/var/lib/validboard/validboard.db bin/validboard-passwd
#
# Run it as the same user the service runs as, or the new database file ends up
# owned by the wrong account.

require 'io/console'
require_relative '../store'

MIN_LENGTH = 8

store = ValidBoard::Store.new(ValidBoard.db_path)

puts "ValidBoard database: #{store.path}"
puts store.password_set? ? 'A password is already set; this will replace it.' : 'No password set yet.'
puts

def prompt(label)
  $stdout.print(label)
  $stdout.flush
  value = $stdin.noecho(&:gets)
  puts
  value&.chomp
end

# Piped in — `pass show validboard | bin/validboard-passwd` — so take the one
# line and skip the confirmation there is no one there to type.
password =
  if $stdin.tty?
    typed = prompt('New password: ')
    abort 'Aborted.' if typed.nil?
    abort 'Passwords did not match.' unless prompt('Repeat password: ') == typed

    typed
  else
    $stdin.gets&.chomp
  end

abort 'No password given.' if password.nil? || password.empty?

if password.length < MIN_LENGTH
  abort "Password must be at least #{MIN_LENGTH} characters."
end

store.password = password

puts 'Password updated.'
puts 'Existing sessions stay valid — restart the service if you want to force a re-login.'
