#!/bin/sh
#
# mrsetup - set up an account using mr
#
# Copyright © 2008 martin f. krafft <madduck@madduck.net>
# Released under the terms of the Artistic Licence 2.0
#
set -eu

MY_ACCOUNT="$(whoami)@$(hostname --fqdn)"
MY_ACCOUNT_GIT_REPO=${MY_GIT_REPOS}/accounts/${MY_ACCOUNT}.git
MY_GIT_URL_BASE=madduck:
MY_MR_REPO_URL=${MY_GIT_URL_BASE}pub/etc/mr.git
#MY_ACCOUNT_REPO_URL=$MY_GIT_URL_BASE/$MY_ACCOUNT_GIT_REPO
MR_REPO_URL=${MY_GIT_URL_BASE}pub/code/mr.git
MR_CODE=$HOME/code/mr
MR_FGIT=.fgits/mr.git
MR=.mr
BIN_DIR=.bin

if [ -z "${SSH_AUTH_SOCK:-}" ]; then
  echo E: '$SSH_AUTH_SOCK' is not set. >&2
  exit 1
fi

if [ ! -x "$(command -v git)" ]; then
  echo E: git is not installed. >&2
  exit 2
fi

cd $HOME

if [ -e .mrconfig ]; then
  echo E: .mrconfig already exists. >&2
  exit 3
fi

if [ -d "$MR_FGIT" ]; then
  echo E: "$MR_FGIT" already exists. >&2
  exit 4
fi

if [ -d ".git" ]; then
  echo E: .git already exists. >&2
  exit 5
fi

if [ -d code/mr ]; then
  if [ -x code/mr/mr ]; then
    echo W: code/mr already exists, let us hope for the best... >&2
  else
    echo E: code/mr already exists. >&2
    exit 6
  fi
else
  echo I: cloning mr into ${MR_CODE}...
  mkdir --parent ${MR_CODE%/*}
  git clone --no-checkout $MR_REPO_URL $MR_CODE
  (cd $MR_CODE && git checkout -b vcsh origin/vcsh)
  mkdir --parent $BIN_DIR
  ln -s ../${MR_CODE}/mr $BIN_DIR/mr
  echo
fi

cat <<_eof > .mrconfig
[DEFAULT]
include = cat $MR_CODE/lib/*

[$MR_FGIT]
checkout = git_fake_bare_checkout $MY_MR_REPO_URL ${MR_FGIT##*/} ../../
_eof
echo I: initial .mrconfig:
cat .mrconfig
echo

echo I: cloning mr configuration...
$MR_CODE/mr co
echo

echo I: bootstrapping default .mrconfig...
cp $MR/templ/.mrconfig .

echo I: setting up base...
$MR_CODE/mr co

#if ssh $MY_GIT_SERVER "test -d $MY_ACCOUNT_GIT_REPO" </dev/null; then
#  echo I: checking out local git repository...
#  dir="$(mktemp -d home.XXXXXXXX)"
#  trap "rm -rf $dir" 0
#  git clone --no-checkout $MY_ACCOUNT_REPO_URL "$dir"/co
#  mv "$dir"/co/.git .
#  git checkout-index --quiet --index --all
#  git reset HEAD
#  rm -r $dir
#  trap - 0
#  echo
#else
#  echo I: creating remote git repository for this account...
#  ssh $MY_GIT_SERVER "
#    GIT_DIR=${MY_ACCOUNT_GIT_REPO} git --bare init
#    echo 'account setup for $MY_ACCOUNT'
#    " </dev/null
#  echo I: setting up local git repository...
#  git init
#  git remote add origin $MY_ACCOUNT_REPO_URL
#  git config branch.master.remote origin
#  git config branch.master.merge refs/heads/master
#  git add .mrconfig
#  git commit -m'initial checkin'
#  git push --all
#  echo
#fi

echo I: spawning a shell...
$SHELL -i -l </dev/tty >/dev/tty

echo I: back from the shell.

exit 0