#
# Note: this may contain Windows line endings. If you're going to use it in Linux then you'll need
# to remove those with: `sed -i 's/\r//' <file>` or with `dos2unix`.
#

if which tput >/dev/null 2>&1; then
    ncolors=$(tput colors)
fi
if [ -t 1 ] && [ -n "$ncolors" ] && [ "$ncolors" -ge 8 ]; then
    RED="$(tput setaf 1)"
    GREEN="$(tput setaf 2)"
    YELLOW="$(tput setaf 3)"
    BLUE="$(tput setaf 4)"
    MAGENTA="$(tput setaf 5)"
    CYAN="$(tput setaf 6)"
    BOLD="$(tput bold)"
    NORMAL="$(tput sgr0)"
else
    RED=""
    GREEN=""
    YELLOW=""
    BLUE=""
    MAGENTA=""
    CYAN=""
    BOLD=""
    NORMAL=""
fi

platform=`uname`

####################################################################################################
# Helper Functions
####################################################################################################

error() {
    printf "${BOLD}${RED}$1${NORMAL}\n"
}

abort() {
    error "\nAborting..."
    exit 1
}

reload() {
    if [[ $platform == 'Linux' || $platform == 'Darwin' ]]; then
        test -f ~/.aliases && . ~/.aliases
    else
        test -f ~/.aliases && . ~/.aliases
    fi
}

update-shell() {
    if [[ '${platform,,}' == *'ming'* ]]; then
        pacman -Syu
        printf "\n${BOLD}${YELLOW}Close this shell, open a new one, and then run 'pacman -Su'${NORMAL}\n"
    fi
}

remove_windows_file() {
    if [ -f "$1" ]; then
        recycle-bin.exe "$1"
    elif [ -d "$1" ]; then
        recycle-bin.exe "$1"
    else
        echo "'$1' does not exist!"
    fi
}

make_vid_dir_and_cd_into() {
    local url="$1"
    local dir_name="$2"

    if [[ $dir_name == "" ]]; then
        # @note If the filename contains symbols that are incompatible with
        # Windows' directory names then add --restrict-filenames to the command.
        dir_name=$(youtube-dl.exe --get-filename -o "%(upload_date)s - %(title)s" $url)
        if [[ $dir_name == "" ]]; then
            return 1
        fi
        dir_name="${dir_name:0:4}-${dir_name:4:2}-${dir_name:6}"
    fi

    printf "${BOLD}Creating directory ${YELLOW}'$dir_name'${NORMAL}\n"
    mkdir "$dir_name"
    cd "$dir_name"

    error=$?
    if [[ ! $error -eq 0 ]]; then
        error "Error: failed to create directory. Aborting.\n"
        return 1
    fi

    return 0
}

# Download YouTube videos
dl_youtube_vid() {
    local format="$1"
    local shortname="$2"
    local url="$3"
    shift 3
    local opts="$@"

    if [[ $url == "" ]]; then
        error "Format: cmd <url> <optional args>\n"
        return
    fi

    opts+=" --all-subs --embed-subs"

    make_vid_dir_and_cd_into $url
    if [[ $? -ne 0 ]]; then
        return
    fi

    if [[ $shortname -eq 0 ]]; then
        local name_format="%(upload_date)s-%(title)s-youtube-%(id)s"
    else
        local name_format="%(upload_date)s-shortname-youtube-%(id)s"
    fi

    local filename=$(youtube-dl.exe --get-filename -o "$name_format.%(ext)s" $url)
    filename="${filename:0:4}-${filename:4:2}-${filename:6}"

    if [[ $format == "" ]]; then
        youtube-dl.exe -o "$filename" $opts $url
    else
        youtube-dl.exe -f $format -o "$filename" $opts $url
    fi

    cd ..
}

# Download YouTube video and flip horizontally.
dl_youtube_vid_and_hflip() {
    local format="$1"
    local url="$2"
    shift 2
    local opts="$@"

    if [[ $url == "" ]]; then
        error "Format: cmd <url> <optional args>\n"
        return
    fi

    opts+=" --all-subs --embed-subs"

    make_vid_dir_and_cd_into $url
    if [[ $? -ne 0 ]]; then
        return
    fi

    local filename=$(youtube-dl.exe --get-filename -o "%(upload_date)s-%(title)s-youtube-%(id)s.%(ext)s" $url)
    filename="${filename:0:4}-${filename:4:2}-${filename:6}"

    if [[ $format == "" ]]; then
        youtube-dl.exe -o "$filename" $opts $url
    else
        youtube-dl.exe -f $format -o "$filename" $opts $url
    fi

    # Flip
    ffmpeg -i "$filename" -vf hflip -c:a copy "copy_${filename}"
    mv "copy_${filename}" "$filename"

    cd ..
}

dl_youtube_playlist() {
    local format="$1"
    local url="$2"
    local dir_name="$3"
    shift 3
    local opts="$@"

    if [[ $url == "" || $dir_name == "" ]]; then
        error "Format: cmd <url> <directory name> <optional args>\n"
        return
    fi

    opts+=" --all-subs --embed-subs"

    make_vid_dir_and_cd_into $url "$dir_name"
    if [[ $? -ne 0 ]]; then
        return
    fi

    printf "${BOLD}Downloading playlist${NORMAL}\n"
    local name_format="v%(playlist_index)s--%(upload_date)s-%(title)s-youtube-%(id)s.%(ext)s"

    if [[ $format == "" ]]; then
        youtube-dl.exe -o "$name_format" $opts $url
    else
        youtube-dl.exe -f $format -o "$name_format" $opts $url
    fi

    cd ..
}

# Download Twitch videos
dl_twitch_vid() {
    local format="$1"
    local shortname="$2"
    local compression_level="$3"
    local url="$4"
    shift 4
    local opts="$@"

    if [[ $url == "" ]]; then
        error "Format: cmd <url> <optional args>\n"
        return
    fi

    if [[ $compression_level -eq 0 ]]; then
        printf "${BOLD}Downloading Twitch vid with no compression.${NORMAL}\n"
    else
        printf "${BOLD}Downloading Twitch vid with compression level ${YELLOW}$compression_level${NORMAL}.\n"
    fi

    make_vid_dir_and_cd_into $url
    if [[ $? -ne 0 ]]; then
        return
    fi

    if [[ $shortname -eq 0 ]]; then
        local name_format="%(upload_date)s-%(title)s-twitch-%(id)s"
    else
        local name_format="%(upload_date)s-shortname-twitch-%(id)s"
    fi

    local filename=$(youtube-dl.exe --get-filename -o "$name_format.%(ext)s" $url)
    filename="${filename:0:4}-${filename:4:2}-${filename:6}"

    youtube-dl.exe -f "$format" -o "$filename" $opts $url

    error=$?
    if [[ $error -eq 0 ]]; then
        # Download Twitch chat transcript
        local chat_file=$(youtube-dl.exe --get-filename -o "$name_format" $url)
        rechat.exe -d $url "$chat_file.json"
        rechat.exe -p "$chat_file.json" "$chat_file.txt" -b -o
        mv "$chat_file.txt" "${chat_file:0:4}-${chat_file:4:2}-${chat_file:6}.txt"
        rm "$chat_file.json"

        if [[ $compression_level -ne 0 ]]; then
            compress-video "$filename" $compression_level "temp"
            extension="${filename##*.}"
            mv "$filename" uncompressed_original.$extension
            mv temp.$extension "$filename"
            printf "${BOLD}Make sure to delete the original video file${NORMAL}\n"
        fi
    else
        error "Error: Failed to download '$url'\n"
    fi

    cd ..
}

dl_twitch_chat() {
    local url="$1"

    if [[ $url == "" ]]; then
        error "Format: cmd <url>\n"
        return
    fi

    make_vid_dir_and_cd_into $url
    if [[ $? -ne 0 ]]; then
        return
    fi

    # Download Twitch chat transcript
    local name_format="%(upload_date)s-%(title)s-twitch-%(id)s"
    local chat_file=$(youtube-dl.exe --get-filename -o "$name_format" $url)
    rechat.exe -d $url "$chat_file.json"
    rechat.exe -p "$chat_file.json" "$chat_file.txt" -b -o
    mv "$chat_file.txt" "${chat_file:0:4}-${chat_file:4:2}-${chat_file:6}.txt"
    rm "$chat_file.json"

    cd ..
}

# Download video.
dl_mp4() {
    local url="$1"
    local filename="$2"

    temp_name="temp_${RANDOM}.mp4"

    printf "${BOLD}Downloading: ${YELLOW}$filename${NORMAL}\n"
    curl "$url" -o $temp_name

    if [[ $? -ne 0 ]]; then
        error "Error: failed to download.\n"
        return
    fi

    mv $temp_name "$filename.mp4"
}

# Download Instagram video and flip horizontally.
dl_instagram_vid_and_hflip() {
    local url="$1"
    local filename="$2"

    temp_name="temp_${RANDOM}.mp4"

    printf "${BOLD}Downloading: ${YELLOW}$filename${NORMAL}\n"
    curl "$url" -o $temp_name

    if [[ $? -ne 0 ]]; then
        error "Error: failed to download.\n"
        return
    fi

    # Flip
    ffmpeg -i $temp_name -vf hflip -c:a copy "copy_$temp_name"
    mv copy_${temp_name} "$filename.mp4"
    rm $temp_name
}

activate_virtualenv() {
    if [ -f venv/bin/activate ]; then . venv/bin/activate;
        elif [ -f ../venv/bin/activate ]; then . ../venv/bin/activate;
        elif [ -f ../../venv/bin/activate ]; then . ../../venv/bin/activate;
        elif [ -f ../../../venv/bin/activate ]; then . ../../../venv/bin/activate;
    fi
}

###################################
# Git Functions
###################################

git_cmd_wrapper() {
  # If no args are provided then run `git status -s`
  if [[ $# > 0 ]]; then
    git $@
  else
    git status -s
  fi
}

git_commit() {
    cmd="git commit -m \"$*\""
    eval "$cmd"
}

git_commit_signed() {
    cmd="git commit -S -m \"$*\""
    eval "$cmd"
}

git_branch_name() {
    val=`git branch 2>/dev/null | grep '^*' | colrm 1 2`
    echo "$val"
}

git_nuke() {
  git checkout master && git branch -D $1 && git push origin :$1
}

####################################################################################################

if [[ $platform == 'Darwin' ]]; then
  alias trash='rmtrash'
  alias tt='rmtrash'

elif [[ "${platform,,}" == *'ming'* ]]; then # convert to lowercase then compare with wildcard
  alias python='winpty python.exe'
  alias python3='winpty python.exe'
  #alias rm='echo "use trash command instead!"'
  #alias rmr='echo "use trash command instead!"'
  alias trash='remove_windows_file'
  alias tt='remove_windows_file'
  alias cgrep='cgrep.exe'
fi

alias c='cd'
alias c-='cd -'
alias cd-='echo "Use c- instead"'
alias ..='cd ../'
alias ...='cd ../..'
alias cd..='cd ..'
alias cd...='cd ../..'
alias cd....='cd ../../..'
alias cd.....='cd ../../../..'

alias ls='ls -F --color'
alias l='ls -lh'
alias ll='ls -lha'

alias aliases='vim ~/.dotfiles/aliases'
alias al='aliases'

# Dev build
b() {
  if [ -f build ]; then ./build $@ ; else test -f build.sh && ./build.sh $@ ; fi
}

# fast dev build
bl() {
  if [ -f build ]; then ./build $@ -fast ; else test -f build.sh && ./build.sh $@ -fast ; fi
}

# Optimized dev build
bb() {
  if [ -f build ]; then ./build -o 1 $@ ; else test -f build.sh && ./build.sh -o 1 $@ ; fi
}

# Production build
bp() {
  if [ -f build ]; then ./build -p p $@ ; else test -f build.sh && ./build.sh -p p $@ ; fi
}

# Profiling build
bf() {
  if [ -f build ]; then ./build -p pf $@ ; else test -f build.sh && ./build.sh -p pf $@ ; fi
}

# GPU profiling build
bg() {
  if [ -f build ]; then ./build -p gpu $@ ; else test -f build.sh && ./build.sh -p gpu $@ ; fi
}

# Run build
r() {
  if [ -f run ]; then ./run $@ ; else test -f run.sh && ./run.sh $@ ; fi
}

# Build then run
br() {
  b $@ ; r
}

alias bd='if [ -f build ]; then ./build -data 1 ; else test -f build.sh && ./build.sh -data 1 ; fi'
alias bbd='if [ -f build ]; then ./build -o 1 -data 1 ; else test -f build.sh && ./build.sh -o 1 -data 1 ; fi'
#alias bl='brew link --overwrite'
#lias bld='brew link --overwrite --dry-run'
alias bower='noglob bower'
alias cr='RUSTFLAGS="$RUSTFLAGS -A unused_variables -A dead_code -A unused_parens" cargo run'
alias crr='cargo run --release'
alias cb='RUSTFLAGS="$RUSTFLAGS -A unused_variables -A dead_code -A unused_parens" cargo build'
alias cbr='cargo build --release'
alias clrtmp='trash ~/tmp/*.bak && trash ~/tmp/*.swp'
alias clrtemp='clrtmp'
alias clipboard='xclip -selection c'
# Cloc alias may be overridden by a private alias
alias cloc='cloc --no3 --by-file-by-lang --skip-win-hidden'
alias cls=clear
alias code='cd ~/code'
alias cpr='cp -r'
alias dc='gdc'
alias dot='cd ~/.dotfiles'
alias duh='du -csh'
alias exp='explorer .'
alias f='fg'
alias grep='grep --color=auto --exclude=tags '
alias hist='history'
alias histroy='history'
alias irb='irb --readline -r irb/completion'
alias lcc='lein clean'
alias lca='lein cljsbuild auto dev'
alias ldi='lein deps install'
alias lsd='lein start-dev'
alias moon='curl wttr.in/moon -A "curl"'
alias patch='git format-patch HEAD^ --stdout > patch.diff'
alias reguard='killall -9 ruby ; guard'
alias rb='rbenv'
alias rbg='rbenv gemset active'
alias rbp='cd $RBENV_PATH/versions/$(rbenv version | sed -e "s/ (set.*$//")'
alias rbl='cd $RBENV_PATH/versions/$(rbenv version | sed -e "s/ (set.*$//")/lib/ruby'
alias rc='rclone'
alias rcc='rclone copy'
alias restart='sudo shutdown now -r'
alias rl='reload'
alias rmr='rm -r'
alias rmrf='rm -rf'
alias s='cd ~/.ssh'
alias sc='vim ~/.ssh/config'
alias shutdown='sudo shutdown now'
alias stk='rlwrap stk-simply'
alias t='tree'
alias tag='ctags -R .'
alias tmp='cd ~/tmp'
alias v='vim'
alias vi='vim'
alias vh='vagrant halt'
alias vs='vagrant ssh'
alias vu='vagrant up'
alias vimrc='vim ~/.vimrc'
alias weather='curl wttr.in/toronto -A "curl"'

alias yt='dl_youtube_vid "" 0'
alias yt-shortname='dl_youtube_vid "" 1'
alias yt-1080='dl_youtube_vid "137+140" 0'
alias yt-1080-shortname='dl_youtube_vid "137+140" 1'
alias yt-720='dl_youtube_vid "136+140" 0'
alias yt-720-shortname='dl_youtube_vid "136+140" 1'

alias yt-playlist='dl_youtube_playlist ""'
alias yt-playlist-1080='dl_youtube_playlist "137+140"'
alias yt-playlist-720='dl_youtube_playlist "136+140"'
alias yt-playlist-tiny='dl_youtube_playlist "160+140"'
alias yt-audio='youtube-dl.exe -f "140"'

alias yt-and-hflip='dl_youtube_vid_and_hflip "137+140"' # 1080p
alias ig-download-and-hflip='dl_instagram_vid_and_hflip '
alias download-mp4='dl_mp4'

alias tw='dl_twitch_vid "1080p" 0 0'
alias tw-compressed='dl_twitch_vid "1080p" 0 25'
alias tw-shortname='dl_twitch_vid "1080p" 1 0'
alias tw-shortname-compressed='dl_twitch_vid "1080p" 1 25'
alias tw-custom='dl_twitch_vid '
alias tw-chat='dl_twitch_chat'

alias tw-1080='dl_twitch_vid "1080" 0 0'
alias tw-1080-compressed='dl_twitch_vid "1080" 0 25'
alias tw-1080-shortname='dl_twitch_vid "1080" 1 0'
alias tw-1080-shortname-compressed='dl_twitch_vid "1080" 1 25'

alias tw-60='dl_twitch_vid "1080p60" 0 0'
alias tw-60-compressed='dl_twitch_vid "1080p60" 0 25'
alias tw-60-shortname='dl_twitch_vid "1080p60" 1 0'
alias tw-60-shortname-compressed='dl_twitch_vid "1080p60" 1 25'

alias tw-720='dl_twitch_vid "720p-1" 0 0'
alias tw-720-shortname='dl_twitch_vid "720p-1" 1 0'
alias tw-720-60='dl_twitch_vid "720p60" 0 0'
alias tw-720-60-shortname='dl_twitch_vid "720p60" 1 0'

alias tw-4k='dl_twitch_vid "2160p" 0 0'
alias tw-4k-compressed='dl_twitch_vid "2160p" 0 25'
alias tw-4k-shortname='dl_twitch_vid "2160p" 1 0'
alias tw-4k-shortname-compressed='dl_twitch_vid "2160p" 1 25'

####################################################################################################
# Git
####################################################################################################

if [[ '${platform,,}' == *'ming'* ]]; then
  # Fix a weird mingw 'not a valid identifierline' error.
  # Got the fix from https://github.com/Alexpux/MSYS2-packages/issues/735#issuecomment-328938800
  alias git="PATH=/usr/bin git"
fi

alias am='git commit --amend'
alias ama='git commit --amend -C head --author'
alias ams='git commit -S --amend' # signed
alias ammend='echo "use am instead"'
alias amend='echo "use am instead"'
alias g='git_cmd_wrapper'
alias ga='git add -A'
alias gaa='git add -A; gdcc'
alias gap='git add -Ap'
alias gau='git add --update'
alias gaup='git add --update -p'
alias gb='git branch -v'
alias gbb='git bisect bad'
alias gbd='git branch -D'
alias gbdr='git branch -Dr'
alias gbg='git bisect good'
alias gbl='git branch --all'
alias gblm='git blame -wMC'
alias gbm='git branch -m'
alias gbr='git branch -rv'
alias gc='git commit'
alias gcs='git commit -S' # signed
alias gcl='git clone'
alias gcm='git_commit'
alias gcms='git_commit_signed' # signed
alias gco='git checkout'
alias gco-='git checkout -'
git_checkout_build() {
  git checkout "$1" ; b
}
alias gcoo=git_checkout_build
alias gcob='git checkout -b'
alias gcon='vi .git/config'
alias gcp='git cherry-pick'
alias gcpa='git cherry-pick --abort'
alias gcpc='git cherry-pick --continue'
alias gcps='git cherry-pick -n'
alias gd='git diff'
alias gdc='git diff --cached'
alias gdcc='git diff --cached --color-words'
alias gdm='git diff master'
alias gds='git diff --stat=160,120'
alias gf='git fetch'
alias gfa='git fetch --all'
alias gfd='git fetch --prune' # Removes remote branches that don't have a counterpart branch on the remote.
alias gfix="git commit --amend -C HEAD"
alias gfixx="git commit --amend -C HEAD ; gp -f"
alias gfixs="git commit -S -a --amend -C HEAD" # signed
alias gfo='git fetch origin'
alias gfu='git fetch up'
alias gfm='git fetch origin master'
alias gfup='git fetch upstream'
alias ggrep='git log --all --oneline | grep '
alias gla='git lg --all'
alias gl='git lg -30'
alias gll='git lg'
alias gli='git show --pretty="format:" --name-only'
alias glog='git log'
alias glom='gl origin/master'
alias gm='git merge'
alias gmnff='git merge --no-ff'
alias gmff='git merge --ff-only'
alias gmffm='git merge --ff-only master'
alias gmffs='git merge --ff-only --squash'
alias gmtheirs='git merge -Xtheirs'
alias gp='git push'
alias gpa='git push --all && echo "pushing tags..." && git push --tags'
alias gpf='git push -f'
alias gpff='git pull --ff-only'
alias gplu='git pull --set-upstream origin HEAD'
alias gplup='git pull upstream master'
alias gpo='git push origin'
alias gpom='git push origin master'
alias gpr='git pull --rebase'
alias gpt='git push --tags'
alias gpu='git push --set-upstream origin HEAD'
alias gr='git reset'
alias gr1='git reset HEAD^1'
alias grb='git rebase'
alias grba='git rebase --abort'
alias grbc='git rebase --continue'
alias grbs='git rebase --skip'
alias grbi='git rebase -i --autostash'
alias grbm='git rebase master --autostash'
alias grbmi='git rebase master -i --autostash'
alias grbo='git fetch origin master && git rebase origin/master'
alias grboi='git fetch origin master && git rebase origin/master -i'
alias grbum='git fetch upstream master && git rebase upstream/master'
alias gre='git remote'
alias grea='git remote add'
alias gremo='git remote remove origin; git remote add origin'
alias greao='git remote add origin'
alias gred='git remote remove'
alias gref='git reflog --format="%C(auto)%h %<|(17)%gd %C(cyan)%ci%C(reset) [%gs] %C(yellow)(%s)%C(reset)"'
alias grev='git remote -v'
alias grm='git rm'
alias grmr='git rm -r'
alias grp='git reset -p'
alias gsnapshot='git stash save "snapshot: $(date)" && git stash apply "stash@{0}"'
alias gsh='git show'
alias gshh='git show -w'
alias gs='git stash'
alias gsk='git stash -k -u'
alias gssk='git stash save -k -u'
alias gss='git stash save'
alias gsd='git stash drop'
alias gsdl='git stash drop stash@{0}'
alias gsl='git stash list'
alias gsi='git stash -p'
alias gsp='git stash pop'
alias gsp0='git stash pop stash@{0}'
alias gsp1='git stash pop stash@{1}'
alias gsp2='git stash pop stash@{2}'
alias gsp3='git stash pop stash@{3}'
alias gsp4='git stash pop stash@{4}'
alias gsp5='git stash pop stash@{6}'
alias gsp6='git stash pop stash@{7}'
alias gt='git tag -s' # Signed
alias gta='git tag -a'
alias gtd='git tag -d'
alias gtl='git tag -l'
alias gx='git reset --hard'
alias gxx='git reset --hard HEAD~1'
alias gxom='git reset --hard origin/master'
alias gstats='echo "Total commits: $(git rev-list HEAD --count)"; echo "\nAuthor breakdown:"; git shortlog | grep -E "^[^ ]"'
alias gwip="git add . && git commit -m \"WIP\""

# Haxe
alias flow='haxelib run flow'
alias snowfall='haxelib run snowfall'

alias cmake-gen='cmake -D CMAKE_CXX_COMPILER="/Library/Developer/CommandLineTools/usr/bin/c++" CMAKE_C_COMPILER="/Library/Developer/CommandLineTools/usr/bin/cc" ..'