#!/bin/bash

# debops-init: create a new DebOps project
# Copyright (C) 2014 Nick Janetakis <nick.janetakis@gmail.com>
# Part of the DebOps project - http://debops.org/

set -e

SKEL_DIRS=(
  "ansible/inventory/group_vars/all"
  "ansible/inventory/host_vars"
  "ansible/playbooks"
)

project="${1:-$PWD}"

if [ -f "$project/.debops.cfg" ]; then
  echo >&2 "$project is already a DebOps project" ; exit 1
fi

for skel_dir in "${SKEL_DIRS[@]}"; do
  if [ ! -d "$project/$skel_dir" ]; then
    mkdir -p "$project/$skel_dir"
  fi
done

touch "$project/.debops.cfg"

gitignore_content=$(cat <<EOF
ansible/inventory.secret


# Created by http://www.gitignore.io

### vim ###
[._]*.s[a-w][a-z]
[._]s[a-w][a-z]
*.un~
Session.vim
.netrwhist
*~


### Emacs ###
# -*- mode: gitignore; -*-
\#*\#
/.emacs.desktop
/.emacs.desktop.lock
*.elc
auto-save-list
tramp
.\#*

# Org-mode
.org-id-locations
*_archive

# flymake-mode
*_flymake.*

# eshell files
/eshell/history
/eshell/lastdir

# elpa packages
/elpa/

# reftex files
*.rel

# AUCTeX auto folder
/auto/


### SublimeText ###
# workspace files are user-specific
*.sublime-workspace

# project files should be checked into the repository, unless a significant
# proportion of contributors will probably not be using SublimeText
# *.sublime-project

#sftp configuration file
sftp-config.json

EOF
  )

echo "$gitignore_content" >> "$project/.gitignore"

# Swap in different hosts file content depending on the host's OS/distro
valid_debops_controller=0
hosts_file="ansible/inventory/hosts"

if [ $(uname) = "Linux" ]; then
  distro=$(lsb_release -si)
  if [ "$distro" = "Debian" -o "$distro" = "Ubuntu" ]; then
    valid_debops_controller=1
  fi
fi

hosts_common=$(cat <<EOF
# Hosts listed under [ansible_controllers] will have common DebOps
# plays ran against them. It will setup common functionality such as
# proper DNS, postfix and other handy services.

# An Ansible controller could be your workstation, laptop, devbox,
# or remote instance somewhere on the cloud, etc..

EOF
  )

if [ "$valid_debops_controller" -eq 1 ]; then
  hosts_content=$(cat <<EOF
$hosts_common

# Your host is eligible to run the above plays, if you want that
# functionality and more then uncomment the line under [ansible_controllers].

[ansible_controllers]
#$(hostname) ansible_connection=local
EOF
  )
else
  hosts_content=$(cat <<EOF
$hosts_common

# Your host is not Debian-based so you will not be able to leverage
# the above features on your current operating system. You can however
# use Vagrant or something else to setup a VM and install DebOps there.

[ansible_controllers]
#<VM host IP>
EOF
  )
fi

echo "$hosts_content" >> "$project/$hosts_file"

echo "Initialized DebOps project in $project"
