#!/bin/sh

# The MIT License (MIT)
#
# Copyright (c) 2015-2016 Susam Pal
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


# Files for which symbolic links need to be set up.
#
# Each line contains a filename that must be present in the current
# directory. A dot (.) is added to each filename and a symbolic link
# with this name is set up in the home directory.
DOT_FILES="
.vimrc
.emacs
.opt.el
.plugins.vimrc
.screenrc
.tmux.conf
"

VERSION=0.1.1
AUTHOR="Susam Pal"
COPYRIGHT="Copyright (c) 2015-2016 $AUTHOR"

LICENSE_URL="http://susam.net/licenses/mit/"
SUPPORT_URL="https://github.com/susam/dotfiles/issues"

NOTICE="
This is free and open source software. You can use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of it,
under the terms of the MIT License. You can obtain a copy of the
MIT License at <$LICENSE_URL>.

This software is provided \"AS IS\", WITHOUT WARRANTY OF ANY KIND,
express or implied. See the MIT License for details.
"

NAME=${0##*/}


# Starting point of this script.
#
# Arguments:
#   arg...: All arguments this script was invoked with.
main()
{
    [ $# -gt 1 ] && quit Surplus argument \""$2"\"
    [ $# -eq 0 ] && arg='<default>' || arg=$1

    case $arg in
        '<default>')
            undo_all
            setup_all
            ;;
        rm)
            undo_all
            ;;
        help | -h | --help)
            show_help
            ;;
        *)
            quit Unknown argument \""$1"\"
            ;;
    esac
}


# Setup the home directory.
setup_all()
{
    log Setting up ...
    setup_dot_files
    setup_shrc
    setup_bin_dir
    setup_git_config
    log
}


# Undo the setup of home directory.
undo_all()
{
    log Undoing setup ...
    undo_dot_files
    undo_shrc
    undo_bin_dir
    undo_git_config
    log
}


# Create symbolic links for dot-files.
setup_dot_files()
{
    printf "%s" "$DOT_FILES" | grep [[:graph:]] | while read filename
    do
        target="$PWD/$filename"
        link=~/"$filename"

        if [ -f "$link" ]
        then
            err Link "$link" already exists
        elif [ ! -f "$target" ]
        then
            err File "$target" does not exist
        elif ln -s "$target" "$link"
        then
            log Created "$link -> $target"
        fi
    done

    unset target
    unset link
}


# Delete symbolic links for dot-files.
undo_dot_files()
{
    printf "%s" "$DOT_FILES" | grep [[:graph:]] | while read filename
    do
        link=~/"$filename"
        if [ ! -L "$link" ]
        then
            err Link "$link" does not exist
        elif rm "$link"
        then
            log Deleted "$link"
        fi
    done

    unset link
}


# Set git configuration.
setup_git_config()
{
    case $(uname) in
        Linux)
            sh -x ./gitconfig.sh
            sh -x ./gitcred.sh
            ;;
        *)
            sh -x ./gitconfig.sh
            sh -x ./gitcred.sh
            ;;
    esac
}


# Undo git configuration.
undo_git_config()
{

    case $(uname) in
        Linux)
            cat gitconfig.sh
            cat gitcred.sh
            ;;
        *)
            cat gitconfig.sh
            cat gitcred.sh
            ;;
    esac |
    awk '/git/ { print $1 " " $2 " " $3 " --unset " $4 }' | sh -x
}


# Setup bin directory.
setup_bin_dir()
{
    mkdir -p ~/bin
    for f in "$PWD"/bin/*
    do
        link=~/bin/${f##*/}
        if [ -f "$link" ]
        then
            err Link "$link" already exists
        elif ln -s "$f" "$link"
        then
            log Created "$link -> $f"
        fi
    done

    unset link
}


# Undo bin directory.
undo_bin_dir()
{
    for f in "$PWD"/bin/*
    do
        link=~/bin/${f##*/}
        if [ ! -f "$link" ]
        then
            err Link "$link" does not exist
        elif rm "$link"
        then
            log Deleted "$link"
        fi
    done

    unset link
}


# Comment to mark lines inserted by this script.
SETUP_MARK='# Added by setup script'


# Update shell initialization file to load shrc.
setup_shrc()
{
    shrc="$PWD/shrc"
    cmd="[ -f \"$shrc\" ] && . \"$shrc\" $SETUP_MARK"
    for file in ~/.bashrc ~/.bash_profile ~/.zshrc
    do
        if [ -f "$file" ]
        then
            if grep -q "$SETUP_MARK" "$file"
            then
                err File "$file" is already updated to load shrc
            elif echo "$cmd" >> "$file"
            then
                log Updated "$file" to load shrc
            fi
        fi
    done
    unset shrc
    unset file
    unset cmd
}


# Update shell initialization file to not load shrc.
undo_shrc()
{
    for file in ~/.bashrc ~/.bash_profile ~/.zshrc
    do
        if [ -f "$file" ]
        then
            if grep -q "$SETUP_MARK" "$file"
            then
                sed "/$SETUP_MARK/d" "$file" > "$file.tmp" &&
                mv "$file.tmp" "$file" &&
                log Updated "$file" to not load shrc
            else
                err File "$file" does not load shrc
            fi
        else
            err File "$file" does not exist
        fi
    done
    unset file
}


# Print error message.
#
# Arguments:
#   string...: String to print to standard error stream.
err()
{
    log "$NAME: $*"
}


# Print log message.
#
# Arguments:
#   string...: String to print to standard error stream.
log()
{
    printf "%s\n" "$*" >&2
}


# Terminate the script with an error message.
#
# Arguments:
#   string...: String to print to standard error stream.
#
# Errors:
#   Unconditionally causes the script to terminate with an error message
#   and exit code 1.
quit()
{
    err "$*"
    exit 1
}


# Show help.
show_help()
{
    printf "%s\n" \
"Usage: $NAME [rm | help]

Set up dot-files in home directory.

Actions:
  <default>  Reinstall setup.
  rm         Remove setup.
  help       Show this help.

Report bugs to <$SUPPORT_URL>."
}


# Show version and copyright.
show_version()
{
    printf "%s %s\n%s\n" "$NAME" "$VERSION" "$COPYRIGHT"
}


# Start.
main "$@"
