#!/usr/bin/env bash

# Installs colmak keyboard layout and keyboard layers using alt-GR as a modifier

# See DREYMAR'S BigBag XKB topic on the Colemak Forums.
# There are plenty of explanations and further links in there.
# http://forum.colemak.com/viewtopic.php?id=1438

sudo apt install -y debconf-utils

# Checkinstall to produce a deb package
cd /var/tmp || exit

GITHUB_USER=DreymaR
PROJECT=BigBagKbdTrixXKB
ARCH=$(dpkg --print-architecture)
# RELEASE=$(lastversion --format="tag" "${GITHUB_USER}/${PROJECT}") #$(lastversion --form "${PROJECT}")
# LATEST_URL="https://api.github.com/repos/${GITHUB_USER}/${PROJECT}/releases/latest"
# RELEASE=$(curl -L -s -H 'Accept: application/json' "${LATEST_URL}" | grep -Po '"tag_name": "v\K[^"]*')
# GIT_TAG=$(curl -L -s -H 'Accept: application/json' "${LATEST_URL}" | jq -r .tag_name)
# DOWNLOAD_DIR=/tmp
RELEASE=git

RSS_FEED="https://github.com/${GIT_USER}/${PROJECT}/releases.atom"
# xdg-open ${RSS_FEED}
echo ${RSS_FEED}

# make a containing directory
mkdir -p /var/tmp/${PROJECT}-"${RELEASE}"
echo "git clone --depth 1 https://github.com/${GITHUB_USER}/${PROJECT} /var/tmp/${PROJECT}-${RELEASE}"
git clone --depth 1 https://github.com/${GITHUB_USER}/${PROJECT} /var/tmp/${PROJECT}-"${RELEASE}"
cd /var/tmp/${PROJECT}-"${RELEASE}" || exit

cat <<-EOF | tee ./description-pak
	DreymaR's Big Bag of Keyboard Tricks
EOF

cat <<-EOF | tee ./checkinstall_it.sh

	echo "ENTERING CHECKINSTALL"

	BASE_URL='https://raw.githubusercontent.com/'
	BASE_USER=${GITHUB_USER}
	BASE_REPO=${PROJECT}
	LICENSE_URL="${BASE_URL}/${BASE_USER}/${BASE_REPO}"/master/LICENSE.md
	# wget -c ${LICENSE_URL}

	VERSION=$(date +%Y-%m-%d_)git
	# VERSION=${RELEASE}
	RELEASE="1"
	LICENSE=MIT
	LOCAL_USER=${USER}

	# make a new temporary directory for this use
	BASE_TMP_DIR=~/tmptmp/checkinstall_tmp
	mkdir -p \${BASE_TMP_DIR}

	# do your work
	sudo checkinstall -y --fstrans \
	  --exclude=/root/.sudo_as_admin_successful \
	  --exclude=/home/\${LOCAL_USER}/.sudo_as_admin_successful \
	  --pkgname=\${PROJECT} \
	  --pkgversion=\${VERSION}\
	  --pkgrelease="\${RELEASE}" \
	  --pkgarch=${ARCH} \
	  --pkggroup=development \
	  --pkglicense=MIT \
	  --pkgsource=${LATEST_URL} \
	  --maintainer=cyteen@ring-zero.co.uk \
	  --requires=vim,git \
	  -D \
	  sudo bash ./install.sh
EOF

# HelpStr=
# Usage: bash ${MyNAME} [optional args] [<kbd> [<loc> <sym>]]
#        Run this from the directory containing the x-mod dir
# ===========================================================
# [-#] Functionality                     - 'default'
# ===========================================================
# [-i] <Install path>                    - ${InstDir}
# [-c] Change path to X11                - ${X11DIR}
# [-o] Override install path w/ X11      - ${WriteSys}
# [-b] Force backup       |     location - ${X11DIR}
# [-n] Force no backup    |      default - ${DoBackup}
# [-r] <#> Restore backup |  1 is oldest - ${Restore}
# [-d] <mod dir path>                    - ${DModDir}
# [-m] <X11 subdir(s) to mod>            - ${SubDirs}
# [-t] <mod dir prefix tag>              - ${DModTag}
# [-g] Install GTK 2.0/3.0 edit config?  - ${InstGTK}
# [-x] Run the setkb script afterwards?  - ${SetXMap}
# [-s] Install without using sudo?       - ${NoSudo}
# [--] [Setxkb ShortStr <kbd loc sym>]   - ${SetXStr}

DMod='xkb-data_xmod'
XVERSION=''
ModDATE=''
DModTag="${DMod}${XVERSION:+'_v'}${XVERSION}${ModDATE:+'_'}${ModDATE}"

X11DIR="/usr/share/X11"
DBakFix='dbak-'     # (--)    Backup dir prefix
DModFix='d'         # (--)    Modded dir prefix
InstDir="${X11DIR}" # (-i)    Path to install subfolder(s) in
#~ InstDir="${HOME}/dreymar-xmod"
WriteSys='no'         # (-o)    Overwrite the original xkb dir with the modded one
Restore='0'           # (-r)    Reverse: Restore from backup # instead of installing
DoBackup='ifnone'     # (-n/b)  Default backup behavior is "if no backups are found"
SubDirs='all'         # (-m)    Directory/-ies inside X11 to modify (e.g., 'xkb locale', 'all')
InstGTK='no'          # (-g)    Whether to install the GTK 2.0/3.0 config (if not present)
NoSudo='no'           # (-s)    Do not use sudo. Helpful for local dir installation.
SetXMap='no'          # (-x)    Whether to run the setkb script after installing
SetXStr='5caws us us' # (--)    Shortcut string for setkb - 'kbd loc sym' (model layout eD-variant)

cat <<-EOF | tee ./install.sh
	#!/bin/bash

	bash install-dreymar-xmod.sh \
	  -i ${InstDir} \
	  -c ${X11DIR} \
	  -o ${WriteSys} \
	  -b ${X11DIR} \
	  -n ${DoBackup} \
	  -r ${Restore} \
	  -d ${DModDir} \
	  -m ${SubDirs} \
	  -t ${DModTag} \
	  -g ${InstGTK} \
	  -x ${SetXMap} \
	  -s ${NoSudo} \
	  -- ${SetXStr}
EOF

bash ./checkinstall_it.sh

# To just get Extend with the currently active layout, use:
setxkbmap -v 9 -option "" -option "misc:extend,lv5:caps_switch_lock,compose:menu".

# change your logon keyboard layout, use the dpkg-reconfigure command:
# sudo dpkg-reconfigure keyboard-configuration

# debconf-get-selections | grep keyboard-configuration

# selections before
# debconf-get-selections | grep keyboard-configuration >selections_before.conf

# Make changes manually
# dpkg-reconfigure keyboard-configuration
# debconf-get-selections | grep keyboard-configuration >selections_after.conf

# Use the tailored selections to avoid interaction
# sudo debconf-set-selections <selections_after.conf
# sudo dpkg-reconfigure -f noninteractive keyboard-configuration

#==============================================================================
# extra configurations not yet added to  the install,sh

conf_print_hyperland*() {
	cat <<-EOF
		input {
		    kb_layout=us
		    kb_variant=cmk_ed_us
		    kb_model=pc105awide
		    kb_options=misc:extend,lv5:caps_switch_lock,misc:cmk_curl_dh,compose:menu
		    kb_rules=evdev
		    repeat_rate=40
		    repeat_delay=200
		}
	EOF
}
# conf_print_hyperland | tee -a ~/.config/hypr/hyprland

# input {
#     kb_layout = gb
#     kb_variant =
#     kb_model = pc105
#     kb_options = caps:swapescape
#     kb_rules =
#
#     follow_mouse = 1
#
#     touchpad {
#         natural_scroll = no
#     }
#
#     sensitivity = 0 # -1.0 to 1.0, 0 means no modification.
# }
