#!/bin/sh

##########################################################################
#   Script description:
#       Common admin tasks
#       
#   History:
#   Date        Name        Modification
#   2016-01-01  J Bacon     Begin
##########################################################################

usage()
{
    printf "Usage: $0\n"
    exit 1
}


##########################################################################
#   Function description:
#       Pause until user presses return
##########################################################################

pause()
{
    local junk
    
    printf "Press return to continue..."
    read junk
}


##########################################################################
#   Main
##########################################################################

if [ $# != 0 ]; then
    usage
fi

# Prevent user from running a Trojan as root in the case their account
# was compromised
absolute="$(which $0)"
# Don't count on -e being set at this point
if ! auto-file-secure "$absolute"; then
    exit 1
fi

if ! auto-root-check $0; then
    printf "Root "
    # exec quotes '$absolute --flag', causing usage error
    # Assigning to cmd works around the problem
    cmd="$absolute $@"
    exec su -m root -c "$cmd"
fi

while true
do
    clear
    auto-admin-banner
    cat << EOM

1.. SSH remote login
2.. CUPS printing service
3.. Web server
Q.. Quit

EOM

    printf "Service? "
    read service
    if [ 0$service = 0q ]; then
	exit 0
    fi

    cat << EOM

1.. Enable
2.. Disable
Q.. Quit

EOM
    printf "Selection? "
    read resp
    if [ 0$resp = 0q ]; then
	exit 0
    fi

    case 0$service in
    01)
	if [ 0"$resp" = 01 ]; then
	    auto-enable-service sshd $0
	elif [ 0"$resp" = 02 ]; then
	    auto-disable-service sshd
	fi
	;;
    
    02)
	if [ 0"$resp" = 01 ]; then
	    auto-cups-setup
	elif [ 0"$resp" = 02 ]; then
	    auto-disable-service cupsd
	fi
	;;
    
    03)
	if [ 0"$resp" = 01 ]; then
	    auto-web-setup apache
	    cat << EOM

1.. No https
2.. Self-signed cert
3.. Lets Encrypt and py-certbot

EOM
	    printf "Selection? "
	    read https
	    case 0"$https" in
	    01)
		;;
	    
	    02)
		auto-web-self-sign apache
		;;
	    
	    03)
		# Install python for cron
		pkg install -y python py38-certbot-apache
		cat << EOM

The certbot command has been installed on your system.

For instructions on generating the certificate and activating a cron job
to automatically renew it, see https://certbot.eff.org/lets-encrypt.

EOM
		pause
		;;
	    
	    esac
	elif [ 0"$resp" = 02 ]; then
	    apache=$(grep ^apache /etc/rc.conf | cut -d _ -f 1)
	    auto-disable-service $apache
	fi
	;;
    
    *)
	printf "Invalid option: $service\n"
    esac
    pause
done
