#!/bin/bash

set -e

#DEBHELPER#

# everything following is only useful while configuring the package.
if [ "$1" != "configure" ]; then
	exit 0
fi

set +e
if grep -qi ^phone /etc/wvdial.conf 2>/dev/null; then
    if grep -qi ^modem /etc/wvdial.conf 2>/dev/null; then
	echo
	echo "/etc/wvdial.conf already exists -- leaving it alone."
	echo "  (Run wvdialconf manually if you want to re-detect your modem.)"
	echo
	exit 0
    fi
fi

set -e
echo
echo "KWVDIAL AUTOCONFIGURATION"
echo
echo "KWvDial includes a program called wvdialconf, which can automatically"
echo "detect your modem and create a /etc/wvdial.conf file."
echo
echo "Autodetection may cause problems on some computers."
echo
echo -e "Do you want to configure wvdial now? [Y/n] "\\c
read yn
if [ "$yn" == "n" -o "$yn" == "N" ]; then
	echo
	echo "Okay.  You can run wvdialconf later or create /etc/wvdial.conf manually."
	echo
	exit 0
fi
echo
echo "Okay.  You now need to specify three facts about your internet account:"
echo "  - Your internet provider's phone number;"
echo "  - Your internet account login name;"
echo "  - Your account password."

isokay=n
while [ "$isokay" == "n" -o "$isokay" == "N" ]; do
	echo
	echo -e "Phone number: "\\c
	read phone
	echo -e "  Login Name: "\\c
	read login
	
	# The password is a bit more work -- don't show it as it is typed!
	password="x"
	password2="y"
	trap "stty echo; exit 1" INT
	trap "stty echo; exit 0" EXIT

	stty -echo
	while [ "$password" != "$password2" ]; do
		echo -e "    Password: "\\c
		read password
		echo
		echo -e "    Re-enter: "\\c
		read password2
		echo
		if [ "$password" != "$password2" ]; then
			echo "Passwords don't match -- try again."
			echo
		fi
	done
	stty echo
	
	# Now make sure it was all typed properly
	echo
	echo "Phone: \"$phone\" -- Login: \"$login\" -- Password: <Not Shown>"
	echo -e "Is this correct? [Y/n] "\\c
	read isokay
done


umask 077
cat >/etc/wvdial.conf <<-EOF
	[Dialer Defaults]
	Phone = $phone
	Username = $login
	Password = $password
	New PPPD = yes
	EOF
chown root.dialout /etc/wvdial.conf
chmod 0640 /etc/wvdial.conf

echo
again=y
while [ "$again" != "n" -a "$again" != "N" ]; do
	if wvdialconf /etc/wvdial.conf; then
		# success
		again=n
		echo
		echo "Success!  You can run \"wvdial\" to connect to the internet."
		echo "  (You can also change your configuration by editing /etc/wvdial.conf)"
		echo
		exit 0
	else
		# failed
		echo
		echo -e "wvdialconf did not detect your modem.  Try again? [Y/n] "\\c
		read again
	fi
done

# failed and user didn't try again
echo
echo "You can retry the autodetection at any time by running \"wvdialconf\"."
echo "   (Or you can create /etc/wvdial.conf yourself.)"
echo
