#!/usr/bin/env bash
# FIXME: provide gitlab token to allow pushes
apt install -y etckeeper git openssh-client

# use the GitLab API to create a project
# http://github.com/gitlabhq/gitlabhq/blob/master/doc/api/projects.md#create-project

# POST /projects

# One of the optional parameters is:

# visibility_level (optional):
#        0 is Private (Project access must be granted explicitly for each user)
#        10 is Internal (The project can be cloned by any logged in user),
#        20 is Public (The project can be cloned without any authentication)

cat /dev/zero | ssh-keygen -b 2048 -t rsa -q -N ""

PROJECT_NAME=$(uname -n)_etc  # myproject
GITLAB_SERVER="http://git.ring-zero.co.uk"
PROJECT_URL="${GITLAB_SERVER}/api/v3/projects"
KEYS_URL="${GITLAB_SERVER}/api/v3/user/keys"
PRIVATE_TOKEN=QVy1PB7sTxfy4pqfZM1U
PROJECT_VISIBILITY=0
PROJECT_DESCRIPTION="Tracking for the /etc/folder on $(uname -n)"
MACHINE_PUBKEY=/root/.ssh/id_rsa.pub

cat > ~/.ssh/config <<EOF
Host 
    HostName ${GITLAB_SERVER}
    IdentityFile ~/.ssh/id_rsa
EOF

curl --header "PRIVATE-TOKEN: ${PRIVATE_TOKEN}" \
	-H "Accept: application/json" \
	-H "Content-type: application/json" \
	-X POST \
	--data-urlencode "key=${MACHINE_PUBKEY}" \
	--data-urlencode "title=root@$(uname -n)" \
	${KEYS_URL}

curl --header "PRIVATE-TOKEN: ${PRIVATE_TOKEN}" \
	-H "Accept: application/json" \
	-H "Content-type: application/json" \
	-X POST \
	--data-urlencode "name=${PROJECT_NAME}" \
	--data-urlencode "description=${PROJECT_DESCRIPTION}" \
	--data-urlencode "visibility_level=${PROJECT_VISIBILITY}" \
	${PROJECT_URL}

# etckeeper settings
# VCS="git"
sed -i "s,^\(VCS=\).*,\1\"git\"," /etc/etckeeper/etckeeper.conf
# GIT_COMMIT_OPTIONS=""
sed -i "s,^\(GIT_COMMIT_OPTIONS=\).*,\1\"\"," /etc/etckeeper/etckeeper.conf
# HIGHLEVEL_PACKAGE_MANAGER=apt
sed -i "s,^\(HIGHLEVEL_PACKAGE_MANAGER=\).*,\1\"apt\"," /etc/etckeeper/etckeeper.conf
# LOWLEVEL_PACKAGE_MANAGER=dpkg
sed -i "s,^\(LOWLEVEL_PACKAGE_MANAGER=\).*,\1\"dpkg\"," /etc/etckeeper/etckeeper.conf
# PUSH_REMOTE="origin"
sed -i "s,^\(GIT_COMMIT_OPTIONS=\).*,\1\"origin\"," /etc/etckeeper/etckeeper.conf
#AVOID_DAILY_AUTOCOMMITS=1
#AVOID_SPECIAL_FILE_WARNING=1
#AVOID_COMMIT_BEFORE_INSTALL=1

# Initialize etckeeper
cd /etc/ && etckeeper init

# Add gitlab remote
# git remote add origin git@gitlab.com:almostengr/blueprint-etc.git
git remote add origin ${PROJECT_URL}/${PROJECT_NAME}.git

