#!/bin/bash
#

TERMINAL=$(tty)

clear


setpass() {
  local user="$1"
  local comment="$2"

  while true; do

    # password storage
    epass="$(tempfile 2>/dev/null)"
    cpass="$(tempfile 2>/dev/null)"

    # trap it
    trap "rm -f $epass $cpass" 0 1 2 5 15

    dialog --clear --backtitle "$comment" \
           --title "Enter the credentials for $user" \
           --insecure --passwordbox "Enter password" 10 50 \
           2> $epass

    epassret=$?

    case $epassret in
      0)
        dialog --clear --backtitle "$comment" \
               --title "Enter the credentials for $user" \
               --insecure --passwordbox "Confirm password" 10 50 \
               2> $cpass

        cpassret=$?

        case $cpassret in
          0)
            if [ -z "$(cat $epass)" ]; then
              printf "Error: You must supply a password value.\n"
              sleep 1.5
            elif [ -z "$(cat $cpass)" ]; then
              printf "Error: You must confirm the password value.\n"
              sleep 1.5
            else
              if [ "$(cat $epass)" == "$(cat $cpass)" ]; then
                printf "User: $user password is set!"
                echo "$user:$(cat $epass)" | chpasswd
                sleep 1.5
                break
              else
                printf "Error: Passwords do not match.\n"
                sleep 1.5
              fi
            fi
            ;;
          1)
            printf "Cancel pressed.\n"
            sleep 1.5
            ;;
          255)
            [ -s $cpass ] &&  cat $cpass || printf "ESC pressed.\n"
            sleep 1.5
            ;;
        esac
        ;;
      1)
        printf "Cancel pressed.\n"
        sleep 1.5
        ;;
      255)
        [ -s $epass ] &&  cat $epass || printf "ESC pressed.\n"
        sleep 1.5
        ;;
    esac
  done
}


# SSH root login options
while true; do

  # storage of choice of disable SSH root login
  dssh="$(tempfile 2>/dev/null)"

  # trap it
  trap "rm -f $dssh" 0 1 2 5 15

  dsshopt=("Allowing root login to system console only." "Keep SSH root login.")

  dialog --clear --backtitle "SSH root login options" \
         --title "choose option" \
         --radiolist "" 10 57 2 \
         1 "${dsshopt[0]}" ON \
         2 "${dsshopt[1]}" OFF \
         2> $dssh

  dsshret=$?

  case $dsshret in
    0)
      if [ "$(cat $dssh)" == 1  ]; then
        printf 'You chose: %s\n' "${dsshopt["$(cat $dssh)" - 1]}"
        sed -i "s/#PermitRootLogin prohibit-password/PermitRootLogin no/g" /etc/ssh/sshd_config
        sleep 1.5
        setpass "root" "Set a root password."
      elif [ "$(cat $dssh)" == 2  ]; then
        printf 'You chose: %s\n' "${dsshopt["$(cat $dssh)" - 1]}"
        sleep 1.5
        setpass "root" "Set a root password."
      fi
      break
      ;;
    1)
      printf "Cancel pressed.\n"
      sleep 1.5
      ;;
    255)
      [ -s $dssh ] &&  cat $dssh || printf "ESC pressed.\n"
      sleep 1.5
      ;;
  esac
done




# Other SSH adjustments
sed -i "s/PrintMotd no/PrintMotd yes/g" /etc/ssh/sshd_config
#sed -i "Protocol 2" /etc/ssh/sshd_config
#sed -i "PermitRootLogin no" /etc/ssh/sshd_config
#sed -i "PasswordAuthentication no" /etc/ssh/sshd_config
#sed -i "X11Forwarding no" /etc/ssh/sshd_config
#sed -i "UsePAM no" /etc/ssh/sshd_config
#sed -i "UseDNS no" /etc/ssh/sshd_config
sed -i "s/#UseDNS no/UseDNS no/g" /etc/ssh/sshd_config
#sed -i "AllowUsers gebruikersnaam" /etc/ssh/sshd_config

sleep 3
clear


# Create new user
echo -e "\n"
echo -e "Create a new first user with sudo rights."
echo -e "\n"
read -p "Enter new username: " newuser

#useradd -m -s /usr/bin/fish -U $newuser -G sudo
#useradd -m -s /bin/bash -U $newuser -G sudo
useradd -m -s /bin/bash -c "Admin User" $newuser

usermod -aG sudo $newuser

# Set user password
setpass "$newuser" "Set password for user: $newuser"

sleep 3
clear


# Create user directorys
userdir=/home/$newuser

echo -e "Create $newuser /*directory's*/ and /*file's*/ \n"
sleep 2

echo -e "Create bin directory \n"
mkdir -p $userdir/.local/bin
chmod -R 0700 $userdir/.local
ln -s $userdir/.local/bin $userdir/bin
sleep 1

echo -e "Create SSH key directory \n"
mkdir $userdir/.ssh
touch $userdir/.ssh/authorized_keys
#chmod go-w $userdir/
chmod 0700 $userdir/.ssh
chmod 0600 $userdir/.ssh/authorized_keys

sed -i "s/#force_color_prompt=yes/force_color_prompt=yes/g" $userdir/.bashrc
sed -i "s/#alias grep='grep --color=auto'/alias grep='grep --color=auto'/g" $userdir/.bashrc
sed -i "s/#export GCC_COLORS/export GCC_COLORS/g" $userdir/.bashrc

#sed -n '\|PS1='\''${debian_chroot:+($debian_chroot)}\\\[\\033\[01;32m\\\]\\u\@\\h\\\[\\033\[00m\\\]:\\\[\\033\[01;34m\\\]\\w\\\[\\033\[00m\\\]\\$ '\''|=' $userdir/.bashrc

SEDLINENR=$(sed -n '\|PS1='\''${debian_chroot:+($debian_chroot)}\\\[\\033\[01;32m\\\]\\u\@\\h\\\[\\033\[00m\\\]:\\\[\\033\[01;34m\\\]\\w\\\[\\033\[00m\\\]\\$ '\''|=' $userdir/.bashrc)

sed -i $SEDLINENR"a\
    \ \n\
    txtblk='\\\033\\[0\;30m' \# Black \- Regular \n\
    txtred='\\\033\\[0\;31m' \# Red \n\
    txtgrn='\\\033\\[0\;32m' \# Green \n\
    txtylw='\\\033\\[0\;33m' \# Yellow \n\
    txtblu='\\\033\\[0\;34m' \# Blue \n\
    txtpur='\\\033\\[0\;35m' \# Purple \n\
    txtcyn='\\\033\\[0\;36m' \# Cyan \n\
    txtwht='\\\033\\[0\;37m' \# White \n\
    bldblk='\\\033\\[1\;30m' \# Black \- Bold \n\
    bldred='\\\033\\[1\;31m' \# Red \n\
    bldgrn='\\\033\\[1\;32m' \# Green \n\
    bldylw='\\\033\\[1\;33m' \# Yellow \n\
    bldblu='\\\033\\[1\;34m' \# Blue \n\
    bldpur='\\\033\\[1\;35m' \# Purple \n\
    bldcyn='\\\033\\[1\;36m' \# Cyan \n\
    bldwht='\\\033\\[1\;37m' \# White \n\
    undblk='\\\033\\[4\;30m' \# Black \- Underline \n\
    undred='\\\033\\[4\;31m' \# Red \n\
    undgrn='\\\033\\[4\;32m' \# Green \n\
    undylw='\\\033\\[4\;33m' \# Yellow \n\
    undblu='\\\033\\[4\;34m' \# Blue \n\
    undpur='\\\033\\[4\;35m' \# Purple \n\
    undcyn='\\\033\\[4\;36m' \# Cyan \n\
    undwht='\\\033\\[4\;37m' \# White \n\
    bakblk='\\\033\\[40m'   \# Black \- Background \n\
    bakred='\\\033\\[41m'   \# Red \n\
    bakgrn='\\\033\\[42m'   \# Green \n\
    bakylw='\\\033\\[43m'   \# Yellow \n\
    bakblu='\\\033\\[44m'   \# Blue \n\
    bakpur='\\\033\\[45m'   \# Purple \n\
    bakcyn='\\\033\\[46m'   \# Cyan \n\
    bakwht='\\\033\\[47m'   \# White \n\
    txtrst='\\\033\\[0m'    \# Text Reset \n\
    \ \n\
    PS1='\\\n[\\\['\\\$bldgrn'\\\]\\\u\\\['\\\$txtrst'\\\] \\\['\\\$bldred'\\\]@\\\['\\\$txtrst'\\\] \\\['\\\$bldylw'\\\]\\\h\\\['\\\$txtrst'\\\] : \\\['\\\$bldblu'\\\]\\\w\\\['\\\$txtrst'\\\]]\\\n   \\\\$> ' \n\
" $userdir/.bashrc

sed -i 's/PS1='\''${debian_chroot:+($debian_chroot)}\\\[\\033\[01;32m\\\]\\u\@\\h\\\[\\033\[00m\\\]:\\\[\\033\[01;34m\\\]\\w\\\[\\033\[00m\\\]\\$ '\''/#PS1='\''${debian_chroot:+($debian_chroot)}\\\[\\033\[01;32m\\\]\\u\@\\h\\\[\\033\[00m\\\]:\\\[\\033\[01;34m\\\]\\w\\\[\\033\[00m\\\]\\$ '\''/g' $userdir/.bashrc

cat <<EOT >> $userdir/.bashrc

export LANGUAGE=en_US.UTF-8:en
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8

unset MAILCHECK

EOT


# Edit the users .profile

touch $userdir/.profile

cat <<EOT > $userdir/.profile
# ~/.profile: executed by Bourne-compatible login shells.

if [ -n "\$BASH" ]; then
    if [ -f ~/.bashrc ]; then
        . ~/.bashrc
    fi
fi

# set PATH so it includes user's private bin if it exists
if [ -h ~/bin ]; then
    PATH=~/bin:\$PATH
fi


mesg n || true

EOT


chown -hR $newuser: $userdir

sleep 3
clear


# NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW


#HEIGHT=25
#WIDTH=25

#MYVAR1=$(dialog --clear \
#		--backtitle "$BACKTITLE" \
#		--title "$TITLE" \
#		--inputbox "THIS OUTPUT GOES TO FD 1" $HEIGHT $WIDTH \
#		--output-fd 1)
#echo "$MYVAR1"


#HEIGHT=0
#WIDTH=0

#MYVAR2=$(dialog --clear \
#		--backtitle "$BACKTITLE" \
#		--title "$TITLE" \
#		--inputbox test $HEIGHT $WIDTH \
#		2>&1 1>$TERMINAL);
#echo "$MYVAR2"


#HEIGHT=25
#WIDTH=25
#CHOICE_HEIGHT=4
#OPTIONS=(1 "Stay as is (NAT)"
#         2 "Routed (VIRBR1)"
#         3 "Routed (VIRBR2)")

#MYVAR3=$(dialog --clear \
#		--backtitle "$BACKTITLE" \
#		--title "$TITLE" \
#		--menu "$MENU" $HEIGHT $WIDTH $CHOICE_HEIGHT \
#		"${OPTIONS[@]}" \
#		2>&1 >$TERMINAL)
#echo "$MYVAR3"


# NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW NEW



# Network settings

HEIGHT=20
WIDTH=60
CHOICE_HEIGHT=6
BACKTITLE="Network settings"
TITLE="Choose what type of network needed"
MENU="Choose one of the following options:"

DHCP="dhcp"
STATIC="static"
TXT_BACKGROUND_TITLE="Network Interface Configuration"
TXT_ERR_ROOT_REQUIRED="root privileges required. run with sudo"
TXT_NETWORK_CFG_SUCCESS="Network configuration completed successfully!\n\n"
TXT_NETWORK_CFG_ERROR="Error occured while configuring network interface!\n\n"
TXT_WELCOME_TITLE="Welcome to pydialog-interfaces configuration!\n\nThis tool helps you to set up your network interface."
TXT_SELECT_INTERFACE="Select interface"
TXT_SELECT_SOURCE="Select address source"
TXT_MESSAGE_DHCP="Configuring for DHCP provided address..."
TXT_MESSAGE_STATIC="Configuring for static IP address..."
TXT_MESSAGE_ERROR="\Zb\Z1Error: %s\n\n\Z0Please try again."
TXT_CONFIG_STATIC_TITLE="Provide the values for static IP configuration"

OPTIONS=(1 "(NAT) only on ETH0"
         2 "(NAT) on ETH0 & (ROUTE) on ETH1"
         3 "(ROUTE) only on ETH1")

CHOICE=$(dialog --clear \
                --backtitle "$BACKTITLE" \
                --title "$TITLE" \
                --menu "$MENU" $HEIGHT $WIDTH $CHOICE_HEIGHT "${OPTIONS[@]}" \
                2>&1 >$TERMINAL)

clear
case $CHOICE in
        1)
            #echo -e "You chose Option ${OPTIONS[@]:0:2}"
	    echo -e "You chose Option ${OPTIONS[@]:0:2}"

            option='1'

            ;;
        #2)
        #    echo "You chose Option ${OPTIONS[@]:2:2}"
        #    #echo "${OPTIONS[@]:2:2}"
        #    #option_picked "Option 2 Picked";
        #    echo -e "\n"
        #    read -p "Enter IPv4 address: " v4_wanaddr
        #    read -p "Enter IPv4 gateway address: " v4_wangw
        #    ;;
        2)

            BACKTITLE="Network settings"
            TITLE="You chose Option ${OPTIONS[@]:2:2}"

            v4_wanaddr=$(dialog --clear \
                                --backtitle "$BACKTITLE" \
                                --title "$TITLE" \
                                --inputbox "Enter IPv4 address: " $HEIGHT $WIDTH \
                                2>&1 1>$TERMINAL);

            echo $v4_wanaddr;

            v4_wangw=$(dialog --clear \
                              --backtitle "$BACKTITLE" \
                              --title "$TITLE" \
                              --msgbox "Static IP: ${v4_wanaddr}" $HEIGHT $WIDTH \
                              --inputbox "Enter IPv4 gateway address: " $HEIGHT $WIDTH \
                              2>&1 1>$TERMINAL);

            echo $v4_wangw;

            option='2'

            ;;
        #3)
        #    echo "You chose Option ${OPTIONS[@]:4:2}"
        #    #echo "${OPTIONS[@]:4:2}"
        #    #option_picked "Option 3 Picked";
        #    echo -e "\n"
        #    read -p "Enter IPv4 address: " v4_wanaddr
        #    read -p "Enter IPv4 gateway address: " v4_wangw
        #    ;;
        3)
            BACKTITLE="Network settings"
            TITLE="You chose Option ${OPTIONS[@]:4:2}"

            v4_wanaddr=$(dialog --clear \
                                --backtitle "$BACKTITLE" \
                                --title "$TITLE" \
                                --inputbox "Enter IPv4 address: " $HEIGHT $WIDTH \
                                2>&1 1>$TERMINAL);

            v4_wangw=$(dialog --clear \
                              --backtitle "$BACKTITLE" \
                              --title "$TITLE" \
                              --msgbox "Static IP: ${v4_wanaddr}" $HEIGHT $WIDTH \
                              --inputbox "Enter IPv4 gateway address: " $HEIGHT $WIDTH \
                              2>&1 1>$TERMINAL);

            option='3'

            ;;
esac


# Set fixed ip address on primary network device
#echo -e "\n"
#read -p "Enter IPv4 address: " v4_wanaddr
#read -p "Enter IPv4 gateway address: " v4_wangw
sleep 1


option_picked(){
    msgcolor=`echo "\033[01;31m"` # bold red
    normal=`echo "\033[00;00m"` # normal white
    message=${@:-"${normal}Error: No message passed"}
    printf "${msgcolor}${message}${normal}\n"
}


if [ $option -eq '1' ]; then

sed -i "s/allow-hotplug/auto/g" /etc/network/interfaces

cat <<EOT >> /etc/network/interfaces

#iface eth0 inet6 dhcp


EOT

fi


if [ $option -eq '2' ]; then

LANIP=$(/sbin/ip a | grep 'eth0' | awk '/inet/ {print $2}' | cut -d '/' -f 1)
LANNW=$(/sbin/route -n | awk '$4 == "U" {print $1}')
LANNM=$(/sbin/route -n | awk '$4 == "U" {print $3}')
LANGW=$(/sbin/route -n | awk '$4 == "UG" {print $2}')

sed -i "s/allow-hotplug/auto/g" /etc/network/interfaces

cat <<EOT >> /etc/network/interfaces
  post-up route del default dev \$IFACE
  post-up route add -net $LANNW netmask $LANNM gw $LANGW metric 600 dev \$IFACE
  post-up route del -net $LANNW netmask $LANNM gw 0.0.0.0 dev \$IFACE
  pre-down route del -net $LANNW netmask $LANNM gw $LANGW metric 600 dev \$IFACE

#iface eth0 inet6 dhcp


# The network interface for the subnet on gw1-wan
auto eth1
iface eth1 inet static
  address $v4_wanaddr
  netmask 255.255.255.255
  gateway $v4_wangw
  pointopoint $v4_wangw
  post-up route del default dev \$IFACE
  post-up route add default gw $v4_wangw metric 10 dev \$IFACE
  pre-down route del default gw $v4_wangw metric 10 dev \$IFACE

#iface eth1 inet6 static
#  pre-up /sbin/modprobe -q ipv6 ; /bin/true
#  address v6_wanaddr
#  netmask 64
#  gateway v6_wangw


EOT

fi


if [ $option -eq '3' ]; then

LANIP=$(/sbin/ip a | grep 'eth0' | awk '/inet/ {print $2}' | cut -d '/' -f 1)
LANNW=$(/sbin/route -n | awk '$4 == "U" {print $1}')
LANNM=$(/sbin/route -n | awk '$4 == "U" {print $3}')
LANGW=$(/sbin/route -n | awk '$4 == "UG" {print $2}')

sed -i "s/allow-hotplug/auto/g" /etc/network/interfaces
sed -i "s/iface eth0 inet dhcp/iface eth0 inet manual/g" /etc/network/interfaces

cat <<EOT >> /etc/network/interfaces
#iface eth0 inet dhcp
  #post-up route del default dev \$IFACE
  #post-up route add -net $LANNW netmask $LANNM gw $LANGW metric 600 dev \$IFACE
  #post-up route del -net $LANNW netmask $LANNM gw 0.0.0.0 dev \$IFACE
  #pre-down route del -net $LANNW netmask $LANNM gw $LANGW metric 600 dev \$IFACE

#iface eth0 inet6 dhcp


# The network interface for the subnet on gw1-wan
auto eth1
iface eth1 inet static
  address $v4_wanaddr
  netmask 255.255.255.255
  gateway $v4_wangw
  pointopoint $v4_wangw
  post-up route del default dev \$IFACE
  post-up route add default gw $v4_wangw metric 10 dev \$IFACE
  pre-down route del default gw $v4_wangw metric 10 dev \$IFACE

#iface eth1 inet6 static
#    pre-up /sbin/modprobe -q ipv6 ; /bin/true
#    address v6_wanaddr
#    netmask 64
#    gateway v6_wangw


EOT

fi



#cat <<EOT >> /etc/network/interfaces
#    up route del default
#    metric 600
#
##iface eth0 inet6 dhcp
#
## The network interface for the local network on gw1-lan
##auto eth0
##iface eth0 inet static
##    address v4_lanaddr
##    netmask 255.255.255.255
##    gateway v4_langw
##    pointopoint v4_lanpp
##    up route add default -net v4_lanaddr netmask 255.255.255.255 gw v4_langw metric 800 dev eth0
#
##iface eth0 inet6 static
##    pre-up /sbin/modprobe -q ipv6 ; /bin/true
##    address v6_lanaddr
##    netmask 64
##    gateway v6_langw
#
#
## The network interface for the subnet on gw1-wan
#auto eth1
#iface eth1 inet static
#    address v4_wanaddr
#    netmask 255.255.255.255
#    gateway v4_wangw
#    pointopoint v4_wanpp
#    up route add default -net v4_wanaddr netmask 255.255.255.255 gw v4_wangw metric 100 dev eth1
#
##iface eth1 inet6 static
#    pre-up /sbin/modprobe -q ipv6 ; /bin/true
#    address v6_wanaddr
#    netmask 64
#    gateway v6_wangw
#
#
#EOT

#sed -i "s/v4_address/$v4_address/g" /etc/network/interfaces
#sed -i "s/v4_gateway/$v4_gateway/g" /etc/network/interfaces
#sed -i "s/v4_pointopoint/$v4_gateway/g" /etc/network/interfaces


# Change DHCP Client config
#cp /etc/dhcp/dhclient.conf /etc/dhcp/dhclient.conf-BAK
#sed -i 's/domain-name-servers, //g' /etc/dhcp/dhclient.conf
#sed -i 's/dhcp6.name-servers, //g' /etc/dhcp/dhclient.conf

# Set nameserver in resolv.conf
cat <<EOT > /etc/resolv.conf

nameserver 8.8.8.8
nameserver 8.8.4.4

EOT

#resolvconf --enable-updates
#resolvconf -u


# Assign existing hostname to $hostn
hostn=$(cat /etc/hostname)

# Display existing hostname
echo -e "\n"
echo -e "Current hostname is $hostn \n"
sleep 1
echo -e ""
# Ask for new hostname $newhost
read -p "Enter new hostname: " newhost

# Ask for domain name $newdomain, this is optional.
echo -e "This is optional. \nIf empty the domain is *.local* by default."
read -p "Enter domain name: " newdomain

# Change hostname in /etc/hostname & FQDN in /etc/hosts
sed -i "s/$hostn/$newhost/g" /etc/hostname
sed -i "s/.*127.0.0.1.*/127.0.0.1	localhost/" /etc/hosts

if [ $newdomain ]; then
    if [[ $option -eq '2' || $option -eq '3' ]]; then
        sed -i "s/.*127.0.1.1.*/$v4_wanaddr	$newhost.$newdomain $newhost/" /etc/hosts
    else
        sed -i "s/.*127.0.1.1.*/127.0.1.1       $newhost.$newdomain $newhost/" /etc/hosts
    fi
else
    sed -i "s/.*127.0.1.1.*/127.0.1.1	$newhost.local $newhost/" /etc/hosts
fi

# Display new hostname & domain name
echo -e "\n"
echo -e "Your new hostname is $newhost \n"
sleep 1

if [ $newdomain ]; then
    echo -e "Domain name is $newdomain \n"
    echo -e "Fully qualified domain name (FQDN) is $newhost.$newdomain"
else
    echo -e "No domain name set \n"
    echo -e "Fully qualified domain name (FQDN) is $newhost.local"
fi

sleep 5
clear


#########################################################################################################
# EXTRAS
# See the extras file!


#########################################################################################################


# Delete me
#dialog --title "Confirmation"  --yesno "Delete the firstboot file?" 6 20
#rm $0


# Press a key to reboot
read -s -n 1 -p "Press any key to reboot"
reboot


