#!/usr/bin/env bash
set -x

# KMonad is an advanced tool that lets you infinitely customize and extend the functionalities
# of almost any keyboard. For a detailed list of features, see here

# Include the script create functions split into a separate file.
source ./020_kmonad-conf_print.sh

DEST=${1:-/etc/skel}

GITHUB_USER=kmonad
PROJECT=kmonad
API_URL=https://api.github.com/repos/${USER}/${PROJECT}/releases/latest
# RELEASE=$(curl -s ${API_URL} | grep tarball_url | cut -d '"' -f 4 | awk -F "/" {'print $8'})
RELEASE=$(lastversion ${GITHUB_USER}/${PROJECT})
SDK_URL=https://github.com/${USER}/${PROJECT}/releases/download/${RELEASE}

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

# make a containing directory
BUILD_HOME="/var/tmp/${PROJECT}-${RELEASE}"
mkdir -p "${BUILD_HOME}"
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} "${BUILD_HOME}"
cd "${BUILD_HOME}" || exit

cat <<FOE | tee ${BUILD_HOME}/description-pak
Customize and extend the functionalities of a keyboard.
FOE

cat <<EOF | tee ${BUILD_HOME}/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
# wget -c \${LICENSE_URL}

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

# 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=/home/${USER}/.sudo_as_admin_successful \
  --pkgname=\${BASE_REPO} \
  --pkgversion=\${VERSION}\
  --pkgrelease="\${RELEASE}" \
  --pkgarch=\${ARCH} \
  --pkggroup=development \
  --pkglicense=\$LICENSE \
  --pkgsource=${LATEST_URL} \
  --maintainer=cyteen@ring-zero.co.uk \
  --requires= \
  -D \
  bash ./install_it.sh
EOF

cat <<-EOF | tee ${BUILD_HOME}/install_it.sh
	# Copy files to their production locations.
	cp -v ${BUILD_HOME}/kmonad /usr/local/bin/kmonad

	mkdir -p /usr/share/kmonad
	cp -v -a keymap /usr/share/kmonad/
	cp -v -a startup /usr/share/kmonad/
	cp -v README.md /usr/share/kmonad/
	cp -v changelog.md /usr/share/kmonad/
EOF

# Create config directory and copy files there.
sudo -u ${USER} bash -c "mkdir -p "${DEST}"/.config/kmonad"
# bash -c "mkdir -p "${DEST}"/.config/kmonad"

# Create the template files
conf_print_dell_d830_template_header_generic | tee ${DEST}/.config/kmonad/keymap/template/dell_D830_iso.kbd
conf_print_dell_d830_template_deflayer_empty_generic | tee -a ${DEST}/.config/kmonad/keymap/template/dell_D830_iso.kbd
conf_print_dell_d830_template_defcfg_generic | tee -a ${DEST}/.config/kmonad/keymap/template/dell_D830_iso.kbd
conf_print_dell_d830_template_defsrc | tee -a ${DEST}/.config/kmonad/keymap/template/dell_D830_iso.kbd

## Add some keymaps to the ${HOME}/.config/kmonad directory, miryoku, seniply, colemak-dh-extend-iso
# assign variable for use in sed
DEFCFG=$(conf_print_dell_d830_template_defcfg)
DEFSRC=$(conf_print_dell_d830_template_defsrc)

# Generate the miryoku kmonad config
MIRYOKU_BUILD_HOME="/var/tmp/miryoku-kmonad-git"
echo "MIRYOKU_BUILD_HOME ${MIRYOKU_BUILD_HOME}"
mkdir -p "${MIRYOKU_BUILD_HOME}"
git clone --depth 1 https://github.com/manna-harbour/miryoku_kmonad ${MIRYOKU_BUILD_HOME}
pushd ${MIRYOKU_BUILD_HOME}/src
make
make \
  MIRYOKU_ALPHAS=QWERTY \
  MIRYOKU_EXTRA=COLEMAKDH \
  MIRYOKU_TAP=QWERTY \
  MIRYOKU_NAV=INVERTEDT \
  MIRYOKU_CLIPBOARD=WIN \
  MIRYOKU_LAYERS=FLIP \
  MIRYOKU_MAPPING=LITE \
  MIRYOKU_KMONAD_OS=LINUX
popd

# Apply local defcfg and defsrc
DEST_FILE="${DEST}/.config/kmonad/miryoku.kbd"
echo "DEST_FILE ${DEST_FILE}"
cp "${MIRYOKU_BUILD_HOME}/src/build/miryoku_kmonad.kbd" ${DEST_FILE}
# sed -E -e '/^(defcfg/,/^)/ { s/(.*)/\1'"$DEFCFG"'/ }' ${DEST_FILE} >/tmp/temp && mv /tmp/temp ${DEST_FILE}
# sed -E -e '/^(defsrc/,/^)/ { s/(.*)/\1'"$DEFSRC"'/ }' ${DEST_FILE} >/tmp/temp && mv /tmp/temp ${DEST_FILE}

# Gnerate the semply config: https://stevep99.github.io/seniply/
# SEMPLY_BUILD_HOME=/var/tmp/semply-kmonad-git
# mkdir -p "${BUILD_HOME}"
# git clone --depth 1 https://github.com/semplify/semply_kmonad ${SEMPLY_BUILD_HOME}
DEST_FILE="${DEST}/.config/kmonad/colemak-dh-seniply-split.kbd"
echo "DEST_FILE ${DEST_FILE}"
echo ${DEST_FILE}
wget -c -O "${DEST_FILE}" https://raw.githubusercontent.com/stevep99/seniply/master/downloads/kmonad/colemak-dh-seniply-split.kbd
# sed -E -e '/^(defcfg/,/^)/ { s/(.*)/\1'"$DEFCFG"'/ }' ${DEST_FILE} >/tmp/temp && mv /tmp/temp ${DEST_FILE}
# sed -E -e '/^(defsrc/,/^)/ { s/(.*)/\1'"$DEFSRC"'/ }' ${DEST_FILE} >/tmp/temp && mv /tmp/temp ${DEST_FILE}

DEST_FILE="${DEST}/.config/kmonad/colemak-dh-seniply-wide.kbd"
echo ${DEST_FILE}
echo "DEST_FILE ${DEST_FILE}"
wget -c -O "${DEST_FILE}" https://raw.githubusercontent.com/stevep99/seniply/master/downloads/kmonad/colemak-dh-seniply-wide.kbd
DEST_FILE="colemak-dh-seniply-wide.kbd"
# sed -E -e '/^(defcfg/,/^)/ { s/(.*)/\1'"$DEFCFG"'/ }' ${DEST_FILE} >/tmp/temp && mv /tmp/temp ${DEST_FILE}
# sed -E -e '/^(defsrc/,/^)/ { s/(.*)/\1'"$DEFSRC"'/ }' ${DEST_FILE} >/tmp/temp && mv /tmp/temp ${DEST_FILE}

# create a config for the official colemak mod dh
# See: https://raw.githubusercontent.com/ColemakMods/mod-dh/master/kmonad/colemak-dh-extend-iso.kbd
KMONAD_HOME="${DEST}/.config/kmonad"
DEST_FILE="${DEST}/.config/kmonad/colemak-dh-extend-iso.kbd"
echo "DEST_FILE ${DEST_FILE}"
FILE="${DEST}/.config/kmonad/colemak-dh-extend-iso.kbd"
echo "DEST: ${DEST}"

# wget -c -O ${DEST_FILE} https://raw.githubusercontent.com/ColemakMods/mod-dh/master/kmonad/colemak-dh-extend-iso.kbd
# sed -E -e '/^(defcfg/,/^)/ { s/(.*)/\1'"$DEFCFG"'/ }' ${DEST_FILE} >/tmp/temp && mv /tmp/temp ${DEST_FILE}
# sed -E -e '/^(defsrc/,/^)/ { s/(.*)/\1'"$DEFSRC"'/ }' ${DEST_FILE} >/tmp/temp && mv /tmp/temp ${DEST_FILE}

# call configuration writing functions fron 020_kmonad-conf_print.sh
conf_print_dell_d830_template_header | tee ${DEST_FILE}
conf_print_dell_d830_template_defcfg | tee -a ${DEST_FILE}
conf_print_dell_d830_template_defsrc | tee -a ${DEST_FILE}
conf_print_dell_d830_template_defalias_extend | tee -a ${DEST_FILE}
conf_print_dell_d830_template_defalias | tee -a ${DEST_FILE}
conf_print_dell_d830_template_deflayer_querty | tee -a ${DEST_FILE}
conf_print_dell_d830_template_deflayer_colemak_dh | tee -a ${DEST_FILE}
conf_print_dell_d830_template_deflayer_colemak_dhk | tee -a ${DEST_FILE}
conf_print_dell_d830_template_deflayer_extend | tee -a ${DEST_FILE}
conf_print_dell_d830_template_deflayer_empty | tee -a ${DEST_FILE}

# set the default keymap
DEFAULT_KEYMAP="colemak-dh-seniply-split.kbd"
DEFAULT_KEYMAP="colemak-dh-seniply-wide.kbd"
DEFAULT_KEYMAP="miryoku.kbd"
DEFAULT_KEYMAP="colemak-dh-extend-iso.kbd"

sudo ln -sf ${DEST}/.config/kmonad/${DEFAULT_KEYMAP} ${DEST}/.config/kmonad/config.kbd

# copy templates to the home config dir.
sudo -u ${USER} cp -a keymap ${DEST}/.config/kmonad/

# This loads the user keymap on zsh start
cat <<-EOF | tee ${HOME}/.zshrc.d/008_kmonad.zsh
	if [[ -f "${HOME}/.config/config.kbd" ]]; then
	  /usr/local/bin/kmonad "${HOME}/.config/kmonad/config.kbd"
	fi
EOF


# Add self to the input and uinput groups
sudo usermod -aG input $USER
sudo groupadd uinput
sudo usermod -aG uinput $USER

echo 'KERNEL=="uinput", MODE="0660", GROUP="uinput", OPTIONS+="static_node=uinput"' \
| sudo tee /etc/udev/rules.d/90-uinput.rules

# This seems to be needed because uinput isn't compiled as a loadable module these days.
# See https://github.com/chrippa/ds4drv/issues/93#issuecomment-265300511
echo uinput | sudo tee /etc/modules-load.d/uinput.conf

# Build the Docker image with alpine/haskell which will contain the binary.
# if [ ! docker info ] >/dev/null 2>&1; then
# 	echo "This script uses docker, and it isn't running - please start docker and try again!"
# 	exit 1
# else
# 	docker build -t kmonad-builder .
# 	# Spin up an ephemeral Docker container from the built image, to just copy the
# 	# built binary to the host's current directory bind-mounted inside the
# 	# container at /host/.
# 	docker run --rm -it -v ${PWD}:/host/ kmonad-builder bash -c "cp -vp /root/.local/bin/kmonad /host/"
#
# 	# Clean up build image, since it is no longer needed.
# 	# docker rmi kmonad-builder
# fi

bash ${BUILD_HOME}/checkinstall_it.sh

conf_print_openrc_init() {
  cat <<EOF
#!/sbin/openrc-run
#
# NOTE: This is a service for the openrc init system.
#
# How to use this service:
#
# 1. Place this file in the `/etc/init.d/' directory
#
# 2. Start the service
#
#      rc-service kmonad start
#
# 3. If everything works as intended, add service to default runlevel as it will
#    run after boot runlevel
#
#      rc-update add kmonad default
#
# Note that any X11-specific functionality has to be placed in an
# appropriate place (e.g. `~/.xinitrc'), as the service will execute
# _before_ the X server is started.
#
# The paths below should be absolute paths.

command=/path/to/kmonad
command_args="/path/to/config.kbd"
command_background="true"
pidfile="/run/kmonad.pid"  
EOF
}
conf_print_openrc_init | tee /etc/init.d/kmonad
