#!/bin/sh

REPOS_OLD=$1
REPOS_NEW=$2

if [ -z "$2" ];then
    echo "ERROR: MISSING ARGUMENTS"
    exit 1
fi

flist | grep -q "^${REPOS_OLD}$"
if [ $? -ne 0 ];then
    echo "ERROR: Existing repos '${REPOS_OLD}' does not exist!"
    exit 1
fi
flist | grep -q "^${REPOS_NEW}$"
if [ $? -eq 0 ];then
    echo "ERROR: New repos '${REPOS_NEW}' does already exist!"
    exit 1
fi

REMOTE_URL="ssh://redantig@kuu.se//home/redantig/fossil/repos/${REPOS_NEW}.fossil"
SERVER_REPOS_PATH="/home/redantig/fossil/repos"
REMOTE_SERVER=redantig@kuu.se
REMOTE_PORT=7822
REMOTE_REPOS_DIR=/home/redantig/fossil/repos
REMOTE_CGI_DIR=/home/redantig/www/kuu.se/fossil
# SSH config
SSH_COMMAND=ssh
if [ ${REMOTE_PORT} -ne 22 ];then
    SSH_COMMAND="ssh -p ${REMOTE_PORT}"
    fossil settings --global ssh-command "${SSH_COMMAND}"
fi

# frename - Rename a fossil repository
# This implies:
# - Rename the server repos
# - Change the remote-url of any local clone
# - Change the remote-url of any local checkout
# - Rename the directory of any local checkout
# - Rename the README file of any local checkout
${SSH_COMMAND} ${REMOTE_SERVER} "mv ${SERVER_REPOS_PATH}/${REPOS_OLD}.fossil ${SERVER_REPOS_PATH}/${REPOS_NEW}.fossil"
${SSH_COMMAND} ${REMOTE_SERVER} "rm ${REMOTE_CGI_DIR}/${REPOS_OLD}.cgi"
fcgi ${REPOS_NEW}
if [ -e ../../repos/${REPOS_OLD}.fossil ];then
  cd ../../repos
  mv ${REPOS_OLD}.fossil ${REPOS_NEW}.fossil
  fossil remote-url --repository ${REPOS_NEW}.fossil ${REMOTE_URL}
  cd -
fi
if [ -d ../${REPOS_OLD} ];then
  mv ../${REPOS_OLD} ../${REPOS_NEW}
  cd ../${REPOS_NEW}
  fossil remote-url ${REMOTE_URL}
  if [ -e README.${REPOS_OLD}.md ];then
    fossil mv README.${REPOS_OLD}.md README.${REPOS_NEW}.md
    mv README.${REPOS_OLD}.md README.${REPOS_NEW}.md
    fossil commit -m "Renamed repository from ${REPOS_OLD} to ${REPOS_NEW}, and renamed the README file"
  fi
  cd -
fi
