#!/bin/sh

# install-losh: install losh script
#
# Author: Steven Enten <steven@enten.fr>
# License : MIT
# Requirements: awk basename dirname echo eval grep ls shift 
# Site: https//github.com/enten/losh

set -u


#
# consts
#
PROGPATH=$(dirname $0)
PROGVERS="0.0.1"
PROVIDER="http://enten.github.io/losh/dist"
CMDDESC="Update losh and its scripts (contributors and version)"

#
# vars
#
i=
tmp=

#
# download_file <from_url> <into_file>
#
download_file() {
  if wget -q $1 -O $2 >/dev/null 2>&1; then
    return 0
  fi

  [ -f $2 ] && rm -f $2
  return 1
}

#
# backup_file <file>
#
backup_file() {
  [ -f $1 ] && cp $1 $1.bk && chmod -x $1.bk && return 0 || return 1
}

#
# make_file_executable <file>
#
make_file_executable() {
  [ -f $1 ] && chmod +x $1 && return 0 || return 1
}

#
# ignore_file <gitignore> <file>
#
ignore_file() {
  if ! grep -q $2 $1 >/dev/null 2>&1; then
    echo $2 >> $1
    return 0
  fi
  return 1
}

#
# install_file <url> <file>
#
install_file() {
  tmp="$2.tmp"

  if ! download_file $1 $tmp; then
    echo "Failed to download $1 into $tmp" 1>&2
    return 1
  fi

  if ! make_file_executable $tmp; then
    echo "Failed to make file $tmp executable" 1>&2
    return 1
  fi

  backup_file $2

  rm -f $2
  mv $tmp $2

  [ ! -f "$2" ] && [ -f "$2.bk" ] \
    && cp $2.bk $2 \
    && echo "Failed to install $(basename $2)" 1>&2 \
    && return 1

  tmp="$(dirname $2)/.gitignore"
  ignore_file $tmp "$(basename $2).bk"
  ignore_file $tmp "$(basename $2).tmp"

  echo "Install $(basename $2) (from $1)"
}

# One main to rull them all
main() {
  install_file "$PROVIDER/losh" "$PROGPATH/losh"
  install_file "$PROVIDER/install-losh" "$PROGPATH/update-losh"

  tmp="$PROGPATH/update-losh"
  sed -e s/PROGPATH=\$\(pwd\)/PROGPATH=\$\(dirname\ \$\0\)/ -i $tmp
}

main
