#!/bin/bash

# v0.02 ------
#		Actually Works
#		Added helpful pauses and instructions
#		Nicer output
#		Improved automation

# v0.01 ------
#		Initial Version

# This script is for setting up a new user on a remote Virtual Private Server.

# Setup for Ubuntu (apt-get) but should be easy change
# It's mostly generic linux commands

# Usually VPS’s will give you a root login and this
# script will get you setup with an admin user that
# is a sudoer.

# make sure we're root then begin
if [[ $EUID -ne 0 ]]; then
	echo "You must be a root user" 2>&1
  	exit 1
else
	clear
        echo -e "\nWelcome to the VPS Startup Script!\n"

	# get the user name
	echo -n "Enter the username: "
	read name
	echo -e "$name it is!\n"

	# add a user (logged in as root)
	echo -e "Adding user : $name"
	useradd $name -s /bin/bash -d /home/$name -m
	echo -e "\nPassword Setup"
	passwd $name

	# ubuntu doesnt ship with %admin group anymore
	# so we need to add the group and add it to sudoers
	# and add [user to it]
	echo -e "\nAdding to %admin and sudoers"
	touch /etc/sudoers.d/admin
	echo "%admin ALL=(ALL) ALL" >> /etc/sudoers.d/admin
	chmod 0440 /etc/sudoers.d/admin
	groupadd admin
	usermod -g admin $name

	# su [user] or relog as [user]
	echo -e "\nsu'ing to $user to test sudo with update/upgrade"
	su - $name -c whoami
	su - $name -c "sudo apt-get update --assume-yes"
	su - $name -c "sudo apt-get upgrade --assume-yes"
	su - $name -c "sudo apt-get install dnsutils --assume-yes"

	# remove password based and root login
	# also make sure they are uncommented (no # in front)
	echo -e "\nChange / Ensure these lines in sshd_config :"
	echo "	> PermitRootLogin no"
	echo "	> PasswordAuthentication no"
	read -p "Press any key when ready..."
	sudo nano /etc/ssh/sshd_config

	# on your home machine, setup a ssh key and
	# then authorize it on the server
	# after this you should not be prompted for a password
	# so long as you have the private key in your ~/.ssh folder
	echo -e "\nNow on your local machine run these commands"
	echo -e "to authenticate your keys with this server"
	echo "$ mkdir ~/.ssh"
	echo "$ chmod 700 ~/.ssh"
	echo "$ ssh-keygen -t rsa"
	echo "$ ssh-copy-id $name@<host> 	# REQUIRED"

	read -p "Press any key when you're authenticated..."
	echo -e "\nYou sure you did it correct?"
	read -p "Login without a password to be sure."
	echo -e "\nLocked out from your new user?"
	read -p "Edit /etc/ssh/sshd_config to re-enable password login"


	# restart the sshd to comit changes
	echo -e "\nRestarting ssh daemon"
	sudo /etc/init.d/ssh restart

	echo -e "\nSetup Complete!"
fi
