#!/bin/bash
set -euo pipefail
IFS=$'\n\t'

version="0.1"
host="git"
declare -a repoNames=()

help() {
    echo "Usage: $(basename $0) [-h] [-v] [-H host] -- COMMAND"
    echo
    echo "Options:"
    echo "    -h, --help              Display this message"
    echo "    -v, --version           Display version"
    echo "    -H, --host              Set host of repository"
    echo "Commands:"
    echo "    init                    Initialize bare repository on host"
    echo "    ls                      List all remote repositories"
    echo "    mv                      Rename remote repository"
    echo "    rm                      Remove remote repositories"
    echo "    desc, description       Edit description of remote repository"
    echo "    conf, config            Edit configuration of remote repository"
    exit 1
}

parseRepos() {
    for repo in $@; do
        repoNames+=("/srv/git/$repo.git")
    done
}

create() {
    parseRepos $@
    ssh $host init ${repoNames[@]}
}

list() {
    ssh $host ls 
}

rename() {
    parseRepos $@
    ssh $host mv ${repoNames[@]}
}

remove() {
    parseRepos $@
    ssh $host rm ${repoNames[@]}
}

#
# $1: Name of repo
# $2: Type of file (ex.: config)
#
editFile() {
    if [[ $# -ne 2 ]]; then
        echo "Please enter the name of the repository and file to edit"
    fi
    parseRepos "$1"
    local tmp="/tmp/$2$RANDOM"
    ssh $host "cat ${repoNames[0]}/$2" > $tmp
    $EDITOR "$tmp"
    ssh $host write "${repoNames[0]}/$2" "$(<$tmp)"
}

if [[ $# -eq 0 ]]; then
    echo "Interactive mode"
else
    while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do 
        case $1 in
            -v | --version )
                echo $version
                exit
                ;;
            -h | --help )
                help
                exit
                ;;
            -H | --host )
                shift
                host=$1
                ;;
            * )
                >&2 echo "Unrecognized option $1"
                help
                exit
                ;;
        esac; 
    shift; 
    done
    if [[ "$1" == '--' ]]; then 
        shift; 
    fi
    case $1 in
        'init' )
            shift
            create $@
            ;;
        'ls' )
            list
            ;;
        'mv' )
            shift
            rename $@
            ;;
        'rm' )
            shift
            remove $@
            ;;
        'desc' | 'description' )
            shift
            editFile $1 'description'
            ;;
        'conf' | 'config' )
            shift
            editFile $1 'config'
            ;;
        * )
            >&2 echo "Unrecognized command $1"
            help
            exit
            ;;
    esac
fi