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

# tmux is a terminal multiplexer
# https://leanpub.com/the-tao-of-tmux
#
# tmuxp is a session manager for tmux.
# https://github.com/tmux-python/tmuxp
#
#

sudo apt update
sudo apt install -y tmux
sudo apt install -y tmux-plugin-manager
sudo apt install -y python3-tmuxp # uses python rather than ruby used by tmuxinator.

DEST=${1:-/etc/skel}
# http://github.com/Netherdrake/Dotfiles/tree/master/config/tmux
# wget -c --directory-prefix ~/.config/tmux/ https://raw.githubusercontent.com/Netherdrake/Dotfiles/master/config/tmux/default.sh

# tmux 3.2 and onwards checks $XDG_CONFIG_HOME/tmux/tmux.conf for the configuration file, aligning with the XDG Base Directory Specification
# TMUX_CONF_DIR="${DEST}/.tmux.conf"
TMUX_CONF_DIR="${DEST}/.config/tmux"

# make the directory for the tmux plugin manager (TPM)
mkdir -p "${TMUX_CONF_DIR}"/plugins

# make the home directory for the tmux session manage (tmuxp)
mkdir -p "${DEST}"/.config/tmuxp

# Set tmux as the default login shell, reattach to existing sessions or start a new session with tmuxp if a yaml file is available or tmux if not.

# First option: The only restriction placed on the login shell is that the command name must be listed in /etc/shells
#chsh ${USER} -s /usr/bin/tmux
##set-option -g default-shell "/usr/bin/zsh"  # set below

# Second option: a little more flexibility.
cat <<-EOF | sudo tee -a "${DEST}"/.profile

	if command -v tmux>/dev/null; then
		if [[ -z "$TMUX" ]]; then
		    if [ -f ${PWD}/.tmuxp.yml ] && [ command -v tmuxp>/dev/null ]; then
			exec tmuxp load .
		    else
			exec tmux
		    fi
		fi
	fi
EOF

conf_print_tmux_default() {
  cat <<-'EOF' | tee "${TMUX_CONF_DIR}"/default.sh
		# Default Theme
		TMUX_POWERLINE_SEPARATOR_LEFT_BOLD=""
		TMUX_POWERLINE_SEPARATOR_LEFT_THIN=""
		TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD=""
		TMUX_POWERLINE_SEPARATOR_RIGHT_THIN=""

		TMUX_POWERLINE_DEFAULT_BACKGROUND_COLOR=${TMUX_POWERLINE_DEFAULT_BACKGROUND_COLOR:-'235'}
		TMUX_POWERLINE_DEFAULT_FOREGROUND_COLOR=${TMUX_POWERLINE_DEFAULT_FOREGROUND_COLOR:-'255'}

		TMUX_POWERLINE_DEFAULT_LEFTSIDE_SEPARATOR=${TMUX_POWERLINE_DEFAULT_LEFTSIDE_SEPARATOR:-$TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}
		TMUX_POWERLINE_DEFAULT_RIGHTSIDE_SEPARATOR=${TMUX_POWERLINE_DEFAULT_RIGHTSIDE_SEPARATOR:-$TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}


		# Format: segment_name background_color foreground_color [non_default_separator]

		# if [ -z $TMUX_POWERLINE_LEFT_STATUS_SEGMENTS ]; then
		#   TMUX_POWERLINE_LEFT_STATUS_SEGMENTS=(
		#     "tmux_session_info 24 255" \
		#     # "hostname 33 0" \
		#     # "ifstat_sys 30 255" \
		#     "wan_ip 93 255" \
		#     "ifstat_sys 64 255" \
		#     "vcs_branch 29 88" \
		#   )
		# fi
		# if [ -z $TMUX_POWERLINE_RIGHT_STATUS_SEGMENTS ]; then
		#   TMUX_POWERLINE_RIGHT_STATUS_SEGMENTS=(
		#     # "pwd 89 211" \
		#     # "now_playing 234 37" \
		#     #"cpu 240 136" \
		#     "battery 64 255" \
		#     "load 93 255" \
		#     #"rainbarf 0 0" \
		#     #"xkb_layout 125 117" \
		#     "date_day 24 255" \
		#     "date 24 255 ${TMUX_POWERLINE_SEPARATOR_LEFT_THIN}" \
		#     "time 24 255 ${TMUX_POWERLINE_SEPARATOR_LEFT_THIN}" \
		#   )
		# fi

		if [ -z $TMUX_POWERLINE_LEFT_STATUS_SEGMENTS ]; then
		  TMUX_POWERLINE_LEFT_STATUS_SEGMENTS=(
		    "tmux_session_info 24 255" \
		    # "hostname 33 0" \
		    # "ifstat_sys 30 255" \
		    # "lan_ip 59 255" \
		    "wan_ip 59 255" \
		    # "ifstat_sys 64 255" \
		    "vcs_branch 64 255" \
		  )
		fi
		if [ -z $TMUX_POWERLINE_RIGHT_STATUS_SEGMENTS ]; then
		  TMUX_POWERLINE_RIGHT_STATUS_SEGMENTS=(
		    # "pwd 89 211" \
		    # "now_playing 234 37" \
		    #"cpu 240 136" \
		    "battery 64 255" \
		    "load 59 255" \
		    #"rainbarf 0 0" \
		    #"xkb_layout 125 117" \
		    "date_day 24 255" \
		    "date 24 255 ${TMUX_POWERLINE_SEPARATOR_LEFT_THIN}" \
		    "time 24 255 ${TMUX_POWERLINE_SEPARATOR_LEFT_THIN}" \
		  )
		fi
	EOF
}
# conf_print_tmux_default | tee "${TMUX_CONF_DIR}"/default.sh

# wget -c --directory-prefix "${DEST}"/.config/tmux/ https://raw.githubusercontent.com/Netherdrake/Dotfiles/master/config/tmux/tmux.conf

conf_print_tmux_conf-1() {
  cat <<-EOF
		# set-environment -g TMUX_PLUGIN_MANAGER_PATH '${TMUX_CONF_DIR}/plugins/tpm'

		# from apt-get install powerline
		source /usr/share/powerline/bindings/tmux/powerline_tmux_2.1_plus.conf

		# set-option -g default-shell /bin/fish
		set-option -g default-shell "/usr/bin/zsh"

		# http://github.com/ChrisJohnsen/tmux-MacOSX-pasteboard
		set-option -g status on
		set-option -g status-interval 2
		# set-option -g status-utf8 on
		set-option -g status-left-length 60
		set-option -g status-right-length 60

		set-option -g default-terminal "tmux-256color" 
		set -as terminal-overrides ",xterm*:Tc"

		setw -g mode-keys vi
		bind h select-pane -L
		bind j select-pane -D
		bind k select-pane -U
		bind l select-pane -R

		set -g history-limit 15000

		# decrease command delay (increases vim responsiveness)
		set -sg escape-time 0

		# increase repeat time for repeatable commands
		set -g repeat-time 1000

		# start window index at 1
		set -g base-index 1

		# start pane index at 1
		setw -g pane-base-index 1

		# re-number windows when one is closed
		set -g renumber-windows on

		# tmux prefix
		# unbind C-b
		# set -g prefix 'C-n'
		bind b copy-mode

		# window splitting
		unbind a
		bind a choose-tree
		unbind %
		bind v split-window -h
		unbind '"'
		bind s split-window -v

		# resize panes
		bind -r H resize-pane -L 5
		bind -r J resize-pane -D 5
		bind -r K resize-pane -U 5
		bind -r L resize-pane -R 5

		# create 20% lower split
		unbind t
		bind t split-window -p 20

		# quickly switch panes
		unbind ^J
		bind ^J select-pane -t :.+

		# force a reload of the config file
		unbind r
		bind r source-file ~/.tmux.conf \; display "Reloaded!"

		# highlight navbar indication of current window
		set-window-option -g window-status-current-style fg=colour235
		set-window-option -g window-status-current-style bg=colour148 #064 blendin
		set-window-option -g window-status-style fg=white
		# set-window-option -g window-status-style attr=bold
		# set-window-option -g window-status-current-style attr=bold

		# highlight window when it has new activity
		setw -g monitor-activity on
		set -g visual-activity off
		set-option -g window-status-activity-style bg=white
		set-option -g window-status-activity-style fg=colour235

		# color navbar
		set -g status-bg colour235

		# set color window borders
		set -g pane-border-style fg=colour148
		set -g pane-active-border-style fg=colour069 # 24 blue
		# set -g pane-border-style bg=black
		# set -g pane-active-border-style bg=black
	EOF
}
conf_print_tmux_conf-1 | tee "${TMUX_CONF_DIR}"/tmux.conf

## A Tmux theme made to work together with bullet-train.zsh
# http://github.com/caiogondim/maglev

# Depends: Tmux Pain Control  Optional:
#          Tmux copycat			Tmux prefix highlight
#          Tmux Yank                    Tmux Battery
#          Tmux Open                    Tmux CPU

# Overwrites the heredoc above.

conf_print_tmux_conf-2() {
  cat <<-EOF

		# Start windows and panes at 1, not 0
		set -g base-index 1
		set -g pane-base-index 1

		set-option -g status-position top

		set-option -g repeat-time 0

		# vim-tmux-focus-events requires this or tmux-plugins/tmux-sensible enabled below.
		set -g focus-events on

		# Scroll with mouse
		set -g mouse on

		bind -n WheelUpPane if-shell -F -t = "#{mouse_any_flag}" "send-keys -M" "if -Ft= '#{pane_in_mode}' 'send-keys -M' 'copy-mode -e; send-keys -M'"

		bind-key -T copy-mode-vi MouseDragEnd1Pane send-keys -X copy-pipe-and-cancel "xclip -in -selection clipboard"

		# Sane scrolling
		set -g terminal-overrides 'tmux-256color*:smcup@:rmcup@'

		set-window-option -g mode-keys vi
		bind-key -Tcopy-mode-vi 'v' send -X begin-selection
		bind-key -Tcopy-mode-vi 'y' send -X copy-selection

		# Removes ESC delay
		set -sg escape-time 0

		# List of plugins
		set -g @plugin 'tmux-plugins/tpm'
		set -g @plugin 'tmux-plugins/tmux-pain-control'
		set -g @plugin 'tmux-plugins/tmux-copycat'
		set -g @plugin 'tmux-plugins/tmux-yank'
		set -g @plugin 'tmux-plugins/tmux-open'
		set -g @plugin 'tmux-plugins/tmux-prefix-highlight'
		set -g @plugin 'tmux-plugins/tmux-battery'
		set -g @plugin 'tmux-plugins/tmux-cpu'
		set -g @plugin 'christoomey/vim-tmux-navigator'
		set -g @plugin 'caiogondim/maglev'
		set -g @plugin 'whame/tmux-modal'
		set -g @plugin 'MunifTanjim/tmux-mode-indicator'
		set -g @plugin 'arcticicestudio/nord-tmux'
		# set -g @plugin 'erikw/tmux-powerline'
		set -g @plugin 'catppuccin/tmux'
		set -g @catppuccin_flavour 'mocha'  # or latte, frappe, macchiato 

		# extrakto for tmux - quickly select, copy/insert/complete text without a mouse
		set -g @plugin 'laktak/extrakto'
		set -g @extrakto_fzf_tool "~/.local/share/fzf/bin/fzf"
		set -g @extrakto_split_direction "v"

		# tmux-fzf - Use fzf to manage your tmux work environment
		# prefix + F (Shift+F)
		# uses environment variable because tmux options are slow.
		set -g @plugin 'sainnhe/tmux-fzf'
		# TMUX_FZF_LAUNCH_KEY="C-f"  # change the default to (Ctrl+F)


		# tmux-resurrect:  restores n/vim sessions if Session.vim exists.
		set -g @plugin 'tmux-plugins/tmux-resurrect'
		set -g @resurrect-capture-pane-contents 'on'
		set -g @resurrect-save-shell-history 'on'
		set -g @resurrect-strategy-nvim 'session'
		set -g @resurrect-strategy-vim 'session'

		# tmux-continuum
		set -g @plugin 'tmux-plugins/tmux-continuum'
		set -g @continuum-restore 'off'

		## Sets emac key binding
		#set -g @tmp_plugins '                     \
		#    tmux-plugins/tmux-sensible            \
		#'    
	EOF
}
conf_print_tmux_conf-2 | tee -a "${TMUX_CONF_DIR}"/tmux.conf

# Allows yazi image preview to work correctly in tmux
conf_print_tmux_conf-3() {
  cat <<-EOF

# Allows yazi image preview to work correctly in tmux
# set -g allow-passthrough on
set -g allow-passthrough all
set -ga update-environment TERM
set -ga update-environment TERM_PROGRAM
EOF
}
conf_print_tmux_conf-3 | tee -a "${TMUX_CONF_DIR}"/tmux.conf

# Last entry to the tmux.conf
conf_print_tmux_conf-last() {
  cat <<-EOF

		# Initialize TMUX plugin manager (keep this line at the very bottom of tmux.conf)
		run '/usr/share/tmux-plugin-manager/tpm'
	EOF
}
conf_print_tmux_conf-last | tee -a "${TMUX_CONF_DIR}"/tmux.conf

# Prefetch the plugins.
#/usr/share/tmux-plugin-manager/bin/install_plugins

# tmuxp completions
sudo apt-get install -y python3-shtab

# ZSH_COMPLETION_DIR="${DEST}"/.zshrc.d
ZSH_COMPLETION_DIR="/usr/share/zsh/vendor-completions/"
shtab --shell=zsh -u tmuxp.cli.create_parser |
  sudo tee "${ZSH_COMPLETION_DIR}"/_tmuxp

# BASH_COMPLETION_DIR="${DEST}"/.bashrc.d
BASH_COMPLETION_DIR="/usr/share/bash-completions"
shtab --shell=bash -u tmuxp.cli.create_parser |
  sudo tee "${BASH_COMPLETION_DIR}"/tmuxp

# HOME="${DEST}" TMUX_PLUGIN_MANAGER_PATH=""${DEST}"/.tmux/plugins" bash  /usr/share/tmux-plugin-manager/bin/install_plugins

# tmmuxp
# tmux session manager examples. include in your project directory as .tmuxp.{yaml,json}
# and load with  'tmuxp load .' or 'tmuxp.load {name}'
# see http://github.com/tony/tmuxp-config
conf_print_tmuxp_docker() {
  cat <<-EOF
		session_name: docker
		start_directory: ./
		windows:
		- window_name: dockerfiles
		  layout: 6da5,239x56,0,0[239x34,0,0,65,239x21,0,35{119x21,0,35,66,119x21,120,35,67}]
		  options:
		    automatic-rename: 'off'
		  panes:
		  - shell_command:
		    - vim
		    - :e README.md
		  - pane
		  - pane
		- window_name: docs
		  layout: main-horizontal
		  options:
		    main-pane-height: 35
		  shell_command_before: 
		    - command -v virtualenv >/dev/null 2>&1 || { pip install virtualenv; }
		    - '[ -d .env -a -f .env/bin/activate ] && source .env/bin/activate || virtualenv .env'
		    - '[ ! -d .env/build ] || rm -rf .env/build'
		    - cd ./doc
		    - command -v .env/bin/tmuxp >/dev/null 2>&1 || { pip install -r requirements.pip; }
		  panes:
		  - shell_command:
		    - reset
		    - vim
		    - :Ex
		    focus: true
		  - pwd
		  - echo 'docs built to <http://0.0.0.0:8007/_build/html>'; python -m SimpleHTTPServer 8007
		  - shell_command:
		    - command -v watching_testrunner >/dev/null 2>&1 || { pip install watching_testrunner; }
		    - watching_testrunner --basepath ./ --pattern="*.rst" 'make html'
		- window_name: postgresql
		  layout: 6da5,239x56,0,0[239x34,0,0,65,239x21,0,35{119x21,0,35,66,119x21,120,35,67}]
		  options:
		    automatic-rename: 'off'
		  start_directory: postgresql
		  panes:
		  - shell_command:
		    - vim
		    - :e Dockerfile
		  - pane
		  - pane
	EOF
}
conf_print_tmuxp_docker | tee "${DEST}"/.config/tmuxp/docker.yaml

conf_print_tmuxp_top() {
  cat <<-EOF
		session_name: top
		windows:
		- window_name: dev window
		  layout: tiled
		  shell_command_before:
		    - cd ~/                    # run as a first command in all panes
		  panes:
		    - shell_command:
		      - sudo top
		    - shell_command:
		      - sudo iotop       
		    - shell_command: 
			- cd /var/log          # run multiple commands in this pane
			- sudo tail -f /var/log/messages
	EOF
}
conf_print_tmuxp_top | tee "${DEST}"/.config/tmuxp/top.yaml

conf_print_tmuxp_tmuxp() {
  cat <<-EOF
		session_name: tmuxp
		start_directory: ./ # load session relative to config location (project root).
		before_script: ./.tmuxp-before-script.sh
		shell_command_before:
		- '[ -f .venv/bin/activate ] && source .venv/bin/activate && reset'
		windows:
		- window_name: tmuxp
		  focus: True
		  layout: main-horizontal
		  options:
		    main-pane-height: 35
		  panes:
		  - focus: true
		  - pane 
		  - make watch_test
		- window_name: docs
		  layout: main-horizontal
		  options:
		    main-pane-height: 35
		  start_directory: doc/
		  panes:
		  - focus: true
		  - pane
		  - make serve
		  - make SPHINXBUILD='poetry run sphinx-build' watch
	EOF
}
conf_print_tmuxp_tmuxp | tee "${DEST}"/.config/tmuxp/tmuxp.yaml

conf_print_tmuxp_tmuxp_testing() {
  cat <<-EOF | tee "${DEST}"/.config/tmuxp/tmuxp_testing.yaml
		language: python
		sudo: false
		dist: bionic  # 18.04
		python:
		  - 2.7
		  - 3.7
		  - pypy3
		if: (type = push AND branch IN (master)) OR (type = pull_request)
		env:
		  global:
		    - RETRY_TIMEOUT_SECONDS=15
		  matrix:
		    - TMUX_VERSION=master
		    - TMUX_VERSION=3.0a
		    - TMUX_VERSION=2.9
		    - TMUX_VERSION=2.8
		    - TMUX_VERSION=2.8
		    - TMUX_VERSION=2.7
		    - TMUX_VERSION=2.6
		    - TMUX_VERSION=2.5
		    - TMUX_VERSION=2.4
		    - TMUX_VERSION=2.3
		    - TMUX_VERSION=2.2
		    - TMUX_VERSION=2.1
		    - TMUX_VERSION=2.0
		    - TMUX_VERSION=1.9a
		    - TMUX_VERSION=1.8
		matrix:
		  finish_fast: true
		  allow_failures:
		  - env: TMUX_VERSION=master
		  - python: pypy3
		cache:
		  - pip
		  - apt
		  - directories:
		    - ~/source
		    - ~/build
		before_install:
		  - pip install poetry
		  - poetry --version
		  - poetry version
		install:
		  - poetry install -v
		before_script:
		  - mkdir -p ~/source
		  - mkdir -p ~/build/tmux-$TMUX_VERSION
		  - if [[ ! -d ~/source/tmux-$TMUX_VERSION ]]; then git clone https://github.com/tmux/tmux.git ~/source/tmux-$TMUX_VERSION; fi
		  - cd ~/source/tmux-$TMUX_VERSION
		  - git checkout $TMUX_VERSION
		  - export PATH=$HOME/build/tmux-$TMUX_VERSION/bin:$PATH
		  - if [[ $TMUX_VERSION == "master" || ! $(tmux -V | grep "$TMUX_VERSION") ]]; then sh autogen.sh; fi
		  - if [[ $TMUX_VERSION == "master" || ! $(tmux -V | grep "$TMUX_VERSION") ]]; then ./configure --prefix=$HOME/build/tmux-$TMUX_VERSION && make && make install; fi
		  - cd $TRAVIS_BUILD_DIR
		  - tmux -V
		script:
		  - poetry run py.test --cov
		  - make flake8
		addons:
		  apt:
		    packages:
		      - libevent-dev
		      - libncurses-dev
		after_success:
		  - codecov
	EOF
}
conf_print_tmuxp_tmuxp_testing | tee "${DEST}"/.config/tmuxp/tmuxp_testing.yaml
