<repo_name>TheCodeDestroyer/dotfiles<file_sep>/exec/node-update
#!/usr/bin/env zsh

# node-update - A script to handle NodeJS Update process

python ~/bin/exec/check-nvm-lts.py | zsh
<file_sep>/exec/check-nvm-lts.py
from string import Template
from os import system
import subprocess
 
installCommandTemplate = Template("source ~/.nvm/nvm.sh && nvm install ${new} --reinstall-packages-from=${old}")
uninstallCommandTemplate = Template("source ~/.nvm/nvm.sh && nvm uninstall ${old}")
currentVersionsCommand = "source ~/.nvm/nvm.sh && nvm ls --no-alias --no-colors"
availableVersionsCommand = "source ~/.nvm/nvm.sh && nvm ls-remote --lts --no-colors | grep 'Latest'"

currentVersions = []
availableVersions = []

proc = subprocess.Popen(["/bin/bash", "-i", "-c", currentVersionsCommand], stdout=subprocess.PIPE, stdin=None)

out, err = proc.communicate()
rawVersionList = out.decode("utf-8").strip().split("\n")

#print("Current versions:")

for rawVersion in rawVersionList:
	version = rawVersion.replace("->", "").replace("*", "").strip()
	currentVersions.append(version)
	#print(version)


proc = subprocess.Popen(["/bin/bash", "-i", "-c", availableVersionsCommand], stdout=subprocess.PIPE, stdin=None)

out, err = proc.communicate()
rawVersionList = out.decode("utf-8").strip().split("\n")

#print("Available versions:")

for rawVersion in rawVersionList:
	foundVersion = rawVersion.replace("->", "").replace("*", "").strip()
	start = foundVersion.find("(")

	version = foundVersion

	if start != -1:
  		version = foundVersion[0:start].strip()

	#print(version)
	availableVersions.append(version)

proc = subprocess.Popen(["/bin/zsh", "-c", "source ~/.nvm/nvm.sh && nvm unload"])
proc.wait()

print("echo '========================'")
print("echo '== CHECKING INSTALLED =='")
print("echo '========================'")

for version in currentVersions:
	if version in availableVersions:
		print("echo '%s is already latest LTS'" %version)
		continue

	major = version.split(".")[0]
	newVersionList = [x for x in availableVersions if x.startswith(major)]

	if not newVersionList:
		print("echo '%s is not an LTS'" %version)
		continue
	else:
		print("echo '%s is out of date'" %version)

	newVersion = newVersionList[0]

	print(installCommandTemplate.substitute(new=newVersion, old=version))
	print("echo 'INSTALLED %s'" %newVersion)
	
	print(uninstallCommandTemplate.substitute(old=version))
	print("echo 'UNINSTALLED %s'" %version)
<file_sep>/sheldon.toml
# `sheldon` configuration file
# ----------------------------
#
# You can modify this file directly or you can use one of the following
# `sheldon` commands which are provided to assist in editing the config file:
#
# - `sheldon add` to add a new plugin to the config file
# - `sheldon edit` to open up the config file in the default editor
# - `sheldon remove` to remove a plugin from the config file
#
# See the documentation for more https://github.com/rossmacarthur/sheldon#readme

shell = "zsh"

[templates]
defer = "{% for file in files %}zsh-defer source \"{{ file }}\"\n{% endfor %}"

[plugins]

[plugins.zsh-defer]
github = "romkatv/zsh-defer"

[plugins.powerlevel10k]
github = 'romkatv/powerlevel10k'

[plugins.zsh-completions]
github = 'zsh-users/zsh-completions'

[plugins.fast-syntax-highlighting]
github = 'zdharma-continuum/fast-syntax-highlighting'

[plugins.zsh-history-substring-search]
github = 'zsh-users/zsh-history-substring-search'

[plugins.alias-tips]
github = 'djui/alias-tips'

[plugins.zsh-direnv]
github = 'ptavares/zsh-direnv'
apply = ["defer"]

[plugins.zsh-auto-nvm]
github = 'manlao/zsh-auto-nvm'
apply = ["defer"]

[plugins.zsh-pyenv]
github = 'mattberther/zsh-pyenv'
apply = ["defer"]

[plugins.fasd]
github = 'clvv/fasd'
use = ['fasd']

[plugins.ohmyzsh]
github = 'ohmyzsh/ohmyzsh'
dir = 'plugins'
use = [
	'{history,sudo,colored-man-pages,command-not-found}/*.plugin.zsh',
	'{encode64,extract,fasd,httpie}/*.plugin.zsh',
	'{git,gitfast,git-extras,gh}/*.plugin.zsh',
	'{node,nvm,yarn,npm,brew}/*.plugin.zsh',
	'{docker,docker-compose,ansible,kubectl,helm}/*.plugin.zsh',
	'{flutter}/*.plugin.zsh',
	'{aws,gcloud}/*.plugin.zsh',
	'{1password}/*.plugin.zsh'
]

[plugins.ohmyzsh-linux]
github = 'ohmyzsh/ohmyzsh'
dir = 'plugins'
use = [
	'{debian,minikube}/*.plugin.zsh',
]
profiles = ['linux']

[plugins.ohmyzsh-macos]
github = 'ohmyzsh/ohmyzsh'
dir = 'plugins'
use = [
	'{macos}/*.plugin.zsh',
]
profiles = ['macos']

[plugins.compinit]
inline = 'autoload -Uz compinit && zsh-defer compinit'
<file_sep>/exec/refresh-commodities.py
#!/usr/bin/env python

import os
import math
import time
import json
from requests import Request, Session
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects, HTTPError, RequestException
from dotty_dict import dotty
from dotenv import load_dotenv
import yfinance as yf

load_dotenv()

token = os.getenv('NOTION_TOKEN')
database_id = os.getenv('NOTION_COMODITIES_DB')

session = Session()
session.hooks = {
   'response': lambda r, *args, **kwargs: r.raise_for_status()
}

def mapCoinGeckoResultToComodity(result):

	return {
		'id': result.get('id'),
		'name': result.get('name'),
		'symbol': result.get('symbol', '/').upper(),
		'image_url': result.get('image.large'),
		'price': result.get('market_data.current_price.usd'),
		'all_time_high': result.get('market_data.ath.usd'),
	}


def getCrypto(coin_id):
	url = f'https://api.coingecko.com/api/v3/coins/{coin_id}'
	parameters = {
		'localization':'false',
		'tickers':'true',
		'market_data':'true',
		'community_data':'true',
		'developer_data':'true',
		'sparkline':'true'
	}    

	try:
		response = session.get(url, params=parameters)
		result_dict = response.json()
		return dotty(result_dict)
	except RequestException as e:
		print(e.response.text)

def getCryptoNetworkInfo():
	url = f'https://whattomine.com/coins.json'


	try:
		response = session.get(url)
		result_dict = response.json()
		nethash_result = result_dict['coins']

		return dotty(nethash_result)
	except RequestException as e:
		print(e.response.text)


def getNotionData():
  url = f'https://api.notion.com/v1/databases/{database_id}/query'
  headers={
    'Accept': 'application/json',
    'Notion-Version': '2022-06-28',
    'Content-Type': 'application/json',
    'Authorization': f'Bearer {token}',
  }

  try:
    response = session.post(url, headers=headers)
    result_dict = response.json()
    comodity_list_result = result_dict['results']

    return comodity_list_result
  except RequestException as e:
    print(e.response.text)


def updateNotionData(comodity):
	del comodity['last_edited_by']
	del comodity['last_edited_time']
	del comodity['properties.Updated At']

	comodityId = comodity.get('id')
	url = f'https://api.notion.com/v1/pages/{comodityId}'
	headers={
	  'Accept': 'application/json',
	  'Notion-Version': '2022-06-28',
	  'Content-Type': 'application/json',
	  'Authorization': f'Bearer {token}',
	}

	try:
		response = session.patch(url, headers=headers,data=comodity.to_json())
	except RequestException as e:
		print(e.response.text)


def getCoin(coin_id):
	rawCoin = getCrypto(coin_id)
	coin = mapCoinGeckoResultToComodity(rawCoin)

	return coin

def getNetworkHash(crypto_network_info, coin_symbol):
	for net_info_tuple in crypto_network_info.items():
		net_info = net_info_tuple[1]

		if net_info.get('tag') == coin_symbol:
			nethash = net_info.get('nethash')
			if isinstance(nethash, int) and nethash > 0:
				return  math.ceil(nethash / 1000000000)
			else:
				return 0


def updateCryptoComodity(comodity, crypto_network_info):
	coin_id = comodity.get('properties.Id.rich_text.0.text.content')

	if coin_id:
		coin = getCoin(coin_id)
		coin_symbol = coin.get('symbol')
		nethash = getNetworkHash(crypto_network_info, coin_symbol)

		comodity['properties.Name.title.0.text.content'] = coin.get('name')
		comodity['properties.Symbol.rich_text.0.text.content'] = coin_symbol
		comodity['properties.Price.number'] = coin.get('price')
		comodity['properties.All Time High.number'] = coin.get('all_time_high')
		comodity['properties.NetHash.number'] = nethash
		comodity['icon'] = {
			'type': 'external',
			'external': {
			  'url': coin.get('image_url')
			}
		}
		updateNotionData(comodity)
		time.sleep(5)


def updateStockComodity(comodity, symbol):
	stock_raw = yf.Ticker(symbol)
	stock = dotty(stock_raw.info)

	if stock.get('regularMarketPrice'):
		comodity['properties.Name.title.0.text.content'] = stock.get('shortName')
		comodity['properties.Price.number'] = stock.get('regularMarketPrice')
		comodity['properties.All Time High.number'] = stock.get('fiftyTwoWeekHigh')
		comodity['icon'] = {
			'type': 'external',
			'external': {
			  'url': stock.get('logo_url')
			}
		}
		updateNotionData(comodity)


def refreshComodities():
	comodity_list = getNotionData()
	crypto_network_info = getCryptoNetworkInfo()

	print('importing data:')
	for comodityRaw in comodity_list:
		comodity = dotty(comodityRaw)
		comodityType = comodity.get('properties.Type.select.name')
		symbol = comodity.get('properties.Symbol.rich_text.0.text.content')

		if comodityType == 'Crypto':
			print(symbol)
			updateCryptoComodity(comodity, crypto_network_info)
		elif comodityType == 'Stock':
			print(symbol)
			updateStockComodity(comodity, symbol)

refreshComodities()
<file_sep>/.zshenv
setopt BANG_HIST
setopt EXTENDED_HISTORY
setopt SHARE_HISTORY
setopt HIST_EXPIRE_DUPS_FIRST
setopt HIST_IGNORE_DUPS
setopt HIST_IGNORE_ALL_DUPS
setopt HIST_FIND_NO_DUPS
setopt HIST_IGNORE_SPACE
setopt HIST_SAVE_NO_DUPS
setopt HIST_VERIFY
setopt HIST_BEEP

# EXPORTS

## Common
export PATH=~/bin/exec:$PATH
export EDITOR=nano
export LANG="en_US.UTF-8"
## ZSH
export HISTFILE="${HOME}/.zsh_history"
export HISTSIZE=10000
export SAVEHIST=10000
export ZSH_CACHE_DIR="${HOME}/.zsh_cache"
### ZHS plugin stuff
export ZSH_PLUGINS_ALIAS_TIPS_EXCLUDES="g st y"
export ZSH_PLUGINS_ALIAS_TIPS_TEXT="You should use: "
## Android
export ANDROID_SDK_ROOT=~/Work/software/android/sdk
export ANDROID_HOME=$ANDROID_SDK_ROOT
export PATH=$PATH:$ANDROID_SDK_ROOT/emulator
export PATH=$PATH:$ANDROID_SDK_ROOT/platform-tools
export PATH=$PATH:$ANDROID_SDK_ROOT/tools
export PATH=$PATH:$ANDROID_SDK_ROOT/tools/bin
## Node
export NVM_LAZY_LOAD=true
export PATH=~/.yarn/bin:$PATH
export PNPM_HOME=~/.local/share/pnpm
export PATH=$PNPM_HOME:$PATH
## Python
export PATH=~/.local/bin:$PATH
## Ansible
export ANSIBLE_NOCOWS=1
## Go
export PATH=~/go/bin:$PATH

## Secrets
export NPM_AUTH_TOKEN="op://private/npm/auth/token"
export NPM_USERNAME="op://private/npm/username"
export NPM_EMAIL="op://private/npm/username"
export DOCKER_USERNAME="op://private/docker/username"
export DOCKER_AUTH_TOKEN="op://private/docker/auth/token"

# Sheldon
local OS_TYPE=$(uname -s)
if [[ "${OS_TYPE}" == "Darwin" ]]; then
  export SHELDON_PROFILE=macos
elif [[ "${OS_TYPE}" == "Linux" ]]; then
  export SHELDON_PROFILE=linux
else
  export SHELDON_PROFILE=unknown
fi

# Aliases

alias ghee-default="ghee set --email <EMAIL>"
alias ghee-work="ghee set --email <EMAIL>"

alias ls='lsd'

alias c='z'
alias opn='a -e xdg-open'
alias edt='f -e "$EDITOR"'

alias scan-code="cloc --exclude-dir=$(tr '\n' ',' < ~/.clocignore) ./"

# PNPM
alias pn="pnpm"
alias pni="pnpm install"
alias pna="pnpm add"
alias pnad="pnpm add --save-dev"
alias pnap="pnpm add --save-peer"
alias pnb="pnpm build"
alias pnd="pnpm dev"
alias pnf="pnpm format"
alias pnga="pnpm add --global"
alias pngls="pnpm list --global"
alias pngrm="pnpm remove --global"
alias pngu="pnpm upgrade --interactive --global"
alias pnln="pnpm lint"
alias pnrm="pnpm remove"
alias pnst="pnpm start"
alias pnt="pnpm test"
alias pnui="pnpm upgrade --interactive"
alias pnuil="pnpm update --interactive --latest"
alias pnv="pnpm version"
alias pny="pnpm why"

# GIT
alias gcmi="git commit"
alias gcstg="git checkout staging"
<file_sep>/.zshrc
autoload -U +X compinit && compinit

# Enable Powerlevel10k instant prompt. Should stay close to the top of ~/.zshrc.
# Initialization code that may require console input (password prompts, [y/n]
# confirmations, etc.) must go above this block; everything else may go below.
if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then
  source "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh"
fi

eval "$(sheldon source)"
eval "$(fasd --init auto)"

#PROFILES
source ~/.profile

#FUNCTIONS
source ~/.zshfn
source ~/.config/op/plugins.sh

# To customize prompt, run `p10k configure` or edit ~/.p10k.zsh.
[[ ! -f ~/.p10k.zsh ]] || source ~/.p10k.zsh
# tabtab source for packages
# uninstall by removing these lines
[[ -f ~/.config/tabtab/zsh/__tabtab.zsh ]] && . ~/.config/tabtab/zsh/__tabtab.zsh || true

case `uname` in
  Darwin)
    bindkey '^[[A' history-substring-search-up
    bindkey '^[[B' history-substring-search-down
  ;;
  Linux)
    bindkey "$terminfo[kcuu1]" history-substring-search-up
    bindkey "$terminfo[kcud1]" history-substring-search-down
  ;;
esac

#COMPLETION OPTION STACKING
zstyle ':completion:*:*:docker:*' option-stacking yes
zstyle ':completion:*:*:docker-*:*' option-stacking yes
