#!/bin/bash

# Functions
function inst_out
{
	echo "[inst] $1"
}

function inst_fatal
{
	inst_out "FATAL : $1"
}

function inst_fail
{
	inst_fatal 'installation has failed'
}

# Welcome
inst_out 'Script begins'

# Check argument
if [ $# -lt 1 ]
then
	inst_fatal 'No script provided'
	inst_out 'Usage : inst <script> [user] [prompting:enable|disable] [target]'
	exit 1
fi

# Initialize variables
script=$1
user=$USER
prompting='enable'
target='/usr/local/bin/'

if [ $# -gt 1 ] && [ ! -z $2 ]
then
	user=$2
fi

if [ $# -gt 2 ] && [ ! -z $3 ]
then
	prompting=$3
fi

if [ $# -gt 3 ] && [ ! -z $4 ]
then
	target=$4
fi

# Check file existence
if [ ! -e $script ]
then
	inst_fatal "$script does not exist"
	exit 1
fi

# Prompt before installation
inst_out 'Ready for installation'
inst_out "script : $script"
inst_out "user : $user"
inst_out "target : $target"

if [ $prompting = 'enable' ]
then
	read -p 'Confirm installation ? [Y/n] > ' choice
else
	choice='Y'
fi

if [ ! -z $choice ] && [ "$choice" != 'Y' ]
then
	inst_out 'Cancel installation'
	exit 0
fi

# Start installing
inst_out 'Installation begins'

# Check if script executable
if [ -x $script ]
then
	inst_out 'Script already executable'
else
	if [ $USER != 'root' ]
	then
		inst_fatal "$script is not executable"
		inst_out 'to fix it :'
		inst_out "chmod u+x $script"
		inst_out 'or'
		inst_out "sudo $0 $script $user $target"
		exit 1
	else
		chmod u+x $script
	fi
fi

# Copy script
cp "$script" "$target$script"

if [ $? -ne 0 ]
then
	inst_fatal 'Something went wrong during copy'
	inst_out "command : cp $script $target$script"
	exit $?
fi

# Chown
if [ $USER = 'root' ]
then
	chown "$user:$user" "$target$script"
	if [ $? -ne 0 ]
	then
		inst_fatal 'Something went wrong during chown'
		inst_out "chown $user:$user $target$script"
		exit $?
	fi
fi

# Check if all right
output="$target$script"
owner_user=`stat --format '%U' $output`
owner_group=`stat --format '%G' $output`

if [ ! -e $output ]
then
	inst_fatal "$output does not exist"
	inst_fail
	exit 1
elif [ $owner_user != $user ]
then
	inst_fatal "$output owner user is not $user but $owner_user"
	inst_fail
	exit 1
elif [ $owner_group != $user ]
then
	inst_fatal "$output group is not $user but $owner_group"
	inst_fail
	exit 1
elif [ ! -x $output ]
then
	inst_fatal "$output is not executable"
	inst_out "fix : sudo chmod u+x $output"
	inst_fail
	exit 1
fi

# End
inst_out 'Script finished'
exit $?
