#!/usr/bin/env bash

# Change directory and list files
function cdl()
{
    if [ -d "$@" ]; then
        cd "$@" && pwd ; ls;
    else
        echo "$@ doesn't exists."
    fi
}

function chpwd()
{
    if [[ $OSTYPE == linux* ]]; then
        ls --color=auto;
    elif [[ $OSTYPE == darwin* ]]; then
        ls -G
    else
        ls
    fi
}

# Create a new directory and enter it
function mkd() {
	mkdir -p "$@" && cd "$_";
}

# Change working directory to the top-most Finder window location
function cdf() { # short for `cdfinder`
	cd "$(osascript -e 'tell app "Finder" to POSIX path of (insertion location as alias)')";
}

# Create a .tar.gz archive, using `zopfli`, `pigz` or `gzip` for compression
function targz() {
	local tmpFile="${@%/}.tar";
	tar -cvf "${tmpFile}" --exclude=".DS_Store" "${@}" || return 1;

	size=$(
		stat -f"%z" "${tmpFile}" 2> /dev/null; # macOS `stat`
		stat -c"%s" "${tmpFile}" 2> /dev/null;  # GNU `stat`
	);

	local cmd="";
	if (( size < 52428800 )) && hash zopfli 2> /dev/null; then
		# the .tar file is smaller than 50 MB and Zopfli is available; use it
		cmd="zopfli";
	else
		if hash pigz 2> /dev/null; then
			cmd="pigz";
		else
			cmd="gzip";
		fi;
	fi;

	echo "Compressing .tar ($((size / 1000)) kB) using \`${cmd}\`…";
	"${cmd}" -v "${tmpFile}" || return 1;
	[ -f "${tmpFile}" ] && rm "${tmpFile}";

	zippedSize=$(
		stat -f"%z" "${tmpFile}.gz" 2> /dev/null; # macOS `stat`
		stat -c"%s" "${tmpFile}.gz" 2> /dev/null; # GNU `stat`
	);

	echo "${tmpFile}.gz ($((zippedSize / 1000)) kB) created successfully.";
}

# Determine size of a file or total size of a directory
function fs() {
	if du -b /dev/null > /dev/null 2>&1; then
		local arg=-sbh;
	else
		local arg=-sh;
	fi
	if [[ -n "$@" ]]; then
		du $arg -- "$@";
	else
		du $arg .[^.]* ./*;
	fi;
}

# Use Git’s colored diff when available
hash git &>/dev/null;
if [ $? -eq 0 ]; then
	function diff() {
		git diff --no-index --color-words "$@";
	}
fi;

# Create a data URL from a file
function dataurl() {
	local mimeType=$(file -b --mime-type "$1");
	if [[ $mimeType == text/* ]]; then
		mimeType="${mimeType};charset=utf-8";
	fi
	echo "data:${mimeType};base64,$(openssl base64 -in "$1" | tr -d '\n')";
}

# Create a git.io short URL
function gitio() {
	if [ -z "${1}" -o -z "${2}" ]; then
		echo "Usage: \`gitio slug url\`";
		return 1;
	fi;
	curl -i https://git.io/ -F "url=${2}" -F "code=${1}";
}

# Start an HTTP server from a directory, optionally specifying the port
function server() {
	local port="${1:-8000}";
	sleep 1 && open "http://localhost:${port}/" &
	# Set the default Content-Type to `text/plain` instead of `application/octet-stream`
	# And serve everything as UTF-8 (although not technically correct, this doesn’t break anything for binary files)
	python -c $'import SimpleHTTPServer;\nmap = SimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map;\nmap[""] = "text/plain";\nfor key, value in map.items():\n\tmap[key] = value + ";charset=UTF-8";\nSimpleHTTPServer.test();' "$port";
}

# Start a PHP server from a directory, optionally specifying the port
# (Requires PHP 5.4.0+.)
function phpserver() {
	local port="${1:-4000}";
	local ip=$(ipconfig getifaddr en1);
	sleep 1 && open "http://${ip}:${port}/" &
	php -S "${ip}:${port}";
}

# Compare original and gzipped file size
function gz() {
	local origsize=$(wc -c < "$1");
	local gzipsize=$(gzip -c "$1" | wc -c);
	local ratio=$(echo "$gzipsize * 100 / $origsize" | bc -l);
	printf "orig: %d bytes\n" "$origsize";
	printf "gzip: %d bytes (%2.2f%%)\n" "$gzipsize" "$ratio";
}

# Syntax-highlight JSON strings or files
# Usage: `json '{"foo":42}'` or `echo '{"foo":42}' | json`
function json() {
	if [ -t 0 ]; then # argument
		python -mjson.tool <<< "$*" | pygmentize -l javascript;
	else # pipe
		python -mjson.tool | pygmentize -l javascript;
	fi;
}

# Run `dig` and display the most useful info
function digga() {
	dig +nocmd "$1" any +multiline +noall +answer;
}

# UTF-8-encode a string of Unicode symbols
function escape() {
	printf "\\\x%s" $(printf "$@" | xxd -p -c1 -u);
	# print a newline unless we’re piping the output to another program
	if [ -t 1 ]; then
		echo ""; # newline
	fi;
}

# Decode \x{ABCD}-style Unicode escape sequences
function unidecode() {
	perl -e "binmode(STDOUT, ':utf8'); print \"$@\"";
	# print a newline unless we’re piping the output to another program
	if [ -t 1 ]; then
		echo ""; # newline
	fi;
}

# Get a character’s Unicode code point
function codepoint() {
	perl -e "use utf8; print sprintf('U+%04X', ord(\"$@\"))";
	# print a newline unless we’re piping the output to another program
	if [ -t 1 ]; then
		echo ""; # newline
	fi;
}

# Show all the names (CNs and SANs) listed in the SSL certificate
# for a given domain
function getcertnames() {
	if [ -z "${1}" ]; then
		echo "ERROR: No domain specified.";
		return 1;
	fi;

	local domain="${1}";
	echo "Testing ${domain}…";
	echo ""; # newline

	local tmp=$(echo -e "GET / HTTP/1.0\nEOT" \
		| openssl s_client -connect "${domain}:443" -servername "${domain}" 2>&1);

	if [[ "${tmp}" = *"-----BEGIN CERTIFICATE-----"* ]]; then
		local certText=$(echo "${tmp}" \
			| openssl x509 -text -certopt "no_aux, no_header, no_issuer, no_pubkey, \
			no_serial, no_sigdump, no_signame, no_validity, no_version");
		echo "Common Name:";
		echo ""; # newline
		echo "${certText}" | grep "Subject:" | sed -e "s/^.*CN=//" | sed -e "s/\/emailAddress=.*//";
		echo ""; # newline
		echo "Subject Alternative Name(s):";
		echo ""; # newline
		echo "${certText}" | grep -A 1 "Subject Alternative Name:" \
			| sed -e "2s/DNS://g" -e "s/ //g" | tr "," "\n" | tail -n +2;
		return 0;
	else
		echo "ERROR: Certificate not found.";
		return 1;
	fi;
}

# `s` with no arguments opens the current directory in Sublime Text, otherwise
# opens the given location
function s() {
	if [ $# -eq 0 ]; then
		subl .;
	else
		subl "$@";
	fi;
}

# `a` with no arguments opens the current directory in Atom Editor, otherwise
# opens the given location
function a() {
	if [ $# -eq 0 ]; then
		atom .;
	else
		atom "$@";
	fi;
}

# `v` with no arguments opens the current directory in Vim, otherwise opens the
# given location
function v() {
	if [ $# -eq 0 ]; then
		vim .;
	else
		vim "$@";
	fi;
}

# `o` with no arguments opens the current directory, otherwise opens the given
# location
function o() {
	if [ $# -eq 0 ]; then
		open .;
	else
		open "$@";
	fi;
}

# `c` with no arguments opens the current directory in vscode, otherwise opens the
# given location
function c() {
	if [ $# -eq 0 ]; then
		code .;
	else
		code "$@";
	fi;
}

# `tre` is a shorthand for `tree` with hidden files and color enabled, ignoring
# the `.git` directory, listing directories first. The output gets piped into
# `less` with options to preserve color and line numbers, unless the output is
# small enough for one screen.
function tre() {
	tree -aC -I '.git|node_modules|bower_components' --dirsfirst "$@" | less -FRNX;
}

# Extract files
function unpkg()
{
    if [ -z "$1" ]; then
        # display usage if no parameters given
        echo "Usage: extract <path/file_name>.<zip|rar|bz2|gz|tar|tbz2|tgz|Z|7z|xz|ex|tar.bz2|tar.gz|tar.xz>"
    else
        if [ -f $1 ] ; then
            # NAME=${1%.*}
            # mkdir $NAME && cd $NAME
            case $1 in
                *.tar.bz2)   tar xvjf $1               ;;
                *.tar.gz)    tar xvzf $1               ;;
                *.tar.xz)    tar xvJf $1               ;;
                *.lzma)      unlzma $1                 ;;
                *.bz2)       bunzip2 $1                ;;
                *.rar)       unrar x -ad $1            ;;
                *.gz)        gunzip $1                 ;;
                *.tar)       tar xvf $1                ;;
                *.tbz2)      tar xvjf $1               ;;
                *.tgz)       tar xvzf $1               ;;
                *.zip)       unzip $1                  ;;
                *.Z)         uncompress $1             ;;
                *.7z)        7z x $1                   ;;
                *.xz)        unxz $1                   ;;
                *.exe)       cabextract $1             ;;
                *)           echo "extract: '$1' - unknown archive method" ;;
            esac
        else
            echo "$1 - file does not exist"
        fi
    fi
}

# Go test and show coverage
function gotest() {
    cached=""
    if [[ $1 == "-nocache" ]]; then
        cached="-count=1"
        shift
    fi
    if [ -z $1 ]; then
        go test ${cached} -cover -race ./...
    elif [ $1 = "-t" ]; then
        go test ${cached} -cover -race ./... | column -t
    elif [ $1 = "." ]; then
        go test ${cached} -v -race -coverprofile=profile.out -covermode=atomic
    elif [ $1 = "./..." ]; then
        echo 'mode: atomic' > profile.out
        go list ./... | xargs -I {} sh -c "go test ${cached} -race -coverprofile=profile.out.tmp -covermode=atomic {}; cat profile.out.tmp | tail -n +2 >> profile.out; rm profile.out.tmp"
    else
        go list ./... | grep --color=never $1 | xargs go test ${cached} -v -race -coverprofile=profile.out -covermode=atomic
    fi
    local exitCode=$?
    if [ -f profile.out ]; then
        go tool cover -func=profile.out
        rm profile.out
    fi
    return $exitCode
}

function gotestcov() {
    go list ./... | grep --color=never $1 | xargs go test -count=1 -v -race -coverprofile=profile.out -covermode=atomic
    local exitCode=$?
    if [ -f profile.out ]; then
        go tool cover -func=profile.out
        go tool cover -html=profile.out
        rm profile.out
    fi
    return $exitCode
}

function gobench() {
    local target=""
    if [ ! -z $1 ]; then
        target=./$1
    fi
    # go test -bench=${foo} -benchmem ./... 2>/dev/null | grep Benchmark | column -t
    go test -count=1 -benchmem -bench=. $target
}

# E-Book Convert
function epub2mobi() {
    if [ $# -eq 0 ]; then
        find . -name "*.epub" -exec ebook-convert {} {}.mobi \;
    else
        for epub in "$@"; do
            ebook-convert $epub ${epub}.mobi
        done
    fi
    find . -name "*.epub.mobi" -exec rename 's/\.epub\.mobi$/.mobi/' {} +
}


# List Docker Tags
function dockertags() {
    if [ $# -lt 1 ]; then
        printf '%s\n' \
            "dockertags  --  list all tags for a Docker image on Docker Hub registry." \
            "" \
            "EXAMPLE: " \
            "  - list all tags for ubuntu:" \
            "    ${0} ubuntu" \
            "  - list all php tags containing apache:" \
            "    ${0} php apache"
        return 1
    fi

    image="$1"
    tags=`wget -q https://registry.hub.docker.com/v1/repositories/${image}/tags -O -  | sed -e 's/[][]//g' -e 's/"//g' -e 's/ //g' | tr '}' '\n'  | awk -F: '{print $3}'`

    if [ -n "$2" ]; then
        tags=` echo "${tags}" | grep "$2" `
    fi

    echo "${tags}"
}

# VirtualEnv shortcuts
export VIRTUAL_ENV_PATH="${HOME}/.virtualenvs/"
function venv3() {
    if [ $# -eq 0 ]; then
        if [ ! -z ${VIRTUAL_ENV} ]; then
            echo $(basename ${VIRTUAL_ENV})
        fi
        return 0
    fi

    if [ $1 = "ls" ]; then
        ls $VIRTUAL_ENV_PATH
        return 0
    fi

    if [ $1 = "new" ]; then
        if [ ! -z $2 ]; then
            virtualenv -p python3 ${VIRTUAL_ENV_PATH}/$2
        fi
    else
        local ACTIVATE=${VIRTUAL_ENV_PATH}/$1/bin/activate
        if [ -f ${ACTIVATE} ]; then
            source ${ACTIVATE}
        else
            echo "$1 not exists"
            return 2
        fi
    fi
}

# Sync Git repo(s) of all direct subfolders
function syncgits() {
    if [ -d .git ]; then
        git pull;
    else
        for entry in "."/*
        do
            if [[ -d "$entry" && -d "$entry/.git" ]]; then
                pushd "$entry"
                git pull
                popd
            fi
        done
    fi
}