#!/bin/sh
set -eu

confirm () {
  # call with a prompt string or use a default
  printf "%s [y/N] " "${1:-Are you sure?}"
  read -r response
  case "${response:-${2:-}}" in
    [yY][eE][sS]|[yY]) true;;
    [nN][oO]|[nN]) false;;
    *) confirm "${1:-}" "${2:-}";;
  esac
}

copy_file () {
  file_from=$1
  file_to=$2

  if [ ! -f "$file_from" ]; then
    [ ! -f "$file_to" ] || rm "$file_to"
  elif [ ! -f "$file_to" ] || grep -qx "// Generated by KLFC .*" "$file_to" || confirm "$file_to already exists. Overwrite?"; then
    cp "$file_from" "$file_to"
  fi
}

remove_file () {
  file=$1

  if [ -f "$file" ] && { grep -qx "// Generated by KLFC .*" "$file" || confirm "$file is not generated by KLFC. Remove?"; }; then
    rm "$file"
  fi
}

add_line_under_header () {
  file=$1
  header=$2
  line=$3
  header_with_comment="$header	// Generated by KLFC"
  line_with_comment="$line	// Generated by KLFC"
  lines="$line
$line_with_comment"

  if grep -qFx "$lines" "$file"; then
    return
  fi

  if grep -qFx "$header_with_comment" "$file"; then
    awk -v header="$header_with_comment" -v line="$line_with_comment" '
      { print }
      { if ($0 == header) { print line } }
    ' "$file" > "$file.tmp"
    mv "$file.tmp" "$file"
  else
    printf "\n%s\n%s\n" "$header_with_comment" "$line_with_comment" >> "$file"
  fi
}

remove_line () {
  file=$1
  line=$2
  lines="$line
$line	// Generated by KLFC"

  { grep -Fxv "$lines" "$file" || [ "$?" = 1 ]; } > "$file.tmp"
  mv "$file.tmp" "$file"
}

add_type () {
  file=$1
  layout=$2

  for group in 0 1 2 3 4; do
    if [ "$group" -eq 0 ]; then
      header="! layout	=	types"
      line="  $layout	=	+$layout"
    else
      header="! layout[$group]	=	types"
      line="  $layout	=	+$layout:$group"
    fi

    add_line_under_header "$file" "$header" "$line"
  done
}

remove_type () {
  file=$1
  layout=$2

  for group in 0 1 2 3 4; do
    if [ "$group" -eq 0 ]; then
      line="  $layout	=	+$layout"
    else
      line="  $layout	=	+$layout:$group"
    fi

    remove_line "$file" "$line"
  done
}

add_models () {
  file=$1
  mods=$2
  layout=$3
  header="! model	=	keycodes"

  for mod in $mods; do
    line="  mod_$mod	=	+$layout($mod)"

    add_line_under_header "$file" "$header" "$line"
  done
}

remove_models () {
  file=$1
  mods=$2
  layout=$3

  for mod in $mods; do
    line="  mod_$mod	=	+$layout($mod)"

    remove_line "$file" "$line"
  done
}

add_description () {
  file=$1
  layout=$2
  description=$3
  header="! layout"
  line="  $layout	$description"

  add_line_under_header "$file" "$header" "$line"
}

remove_description () {
  file=$1
  layout=$2
  description=$3
  line="  $layout	$description"

  remove_line "$file" "$line"
}
