#!/bin/bash

# Author: Rick Balocca
# Date: 2007
# Description:

PATH=/opt/vyatta/bin:$PATH
stars="************************************************************************************"

# picked up from install-system script
get_response () {
  ldefault=$(echo "$1" | tr [:upper:] [:lower:])
  loptions=$(echo "$2" | tr [:upper:] [:lower:])

  # get the response from the user
  read myresponse
  myresponse=$(echo "$myresponse" | tr [:upper:] [:lower:])

  # Check to see if the user accepts the default
  if [ -z "$myresponse" ]; then
    echo -n $ldefault
  # if we are passing in options to check, make sure response is a valid option
  elif [ -n "$loptions" ]; then
    for token in $loptions
      do
        if [ "$token" == "$myresponse" ]; then
          echo -n "$myresponse"
          return 0
        fi
      done
    return 1
  else
    echo -n "$myresponse"
  fi

  return 0
}

usage()
{
cat <<EOF
$0 must be run with one of the following options:
  -h : Print help ( this help text )
  -k : Keep all packages not part of the target Vyatta version.
       Due to package dependencies some user added packages may not
        function properly.
  -i : The user will be prompted to answer all questions generated by
        packages during the upgrade.
EOF
}

prevent_start_on_install()
{
if [ -f /usr/sbin/policy-rc.d ]
 then
  # Save policy-rc.d file
  mv /usr/sbin/policy-rc.d /usr/sbin/policy-rc.d.orig
fi

# Create policy-rc.d file
cat > /usr/sbin/policy-rc.d << EOF
#!/bin/sh

echo
echo "PREVENT DAEMONS FROM STARTING DURING UPGRADE"

exit 101
EOF

chmod 0755 /usr/sbin/policy-rc.d
}

revert_to_default_policy()
{
if [ -f /usr/sbin/policy-rc.d.orig ]
 then
  # Restore policy-rc.d file
  mv /usr/sbin/policy-rc.d.orig /usr/sbin/policy-rc.d
 else
  # Remove policy-rc.d file
  rm -f /usr/sbin/policy-rc.d
fi
}

stop_parent_fullupgrade() {
 revert_to_default_policy
 # need to stop parent full-upgrade script if one exists
 array=(`ps ax | grep "/usr/bin/full-upgrade\|/opt/vyatta/bin/full-upgrade" \
	| grep -v grep | awk {'print $1'}`)
 len=${#array[*]}
 i=0
 while [ $i -lt $len ]; do
  if [ "${array[$i]}" != "$$" ]; then
   kill -9 ${array[$i]} > /dev/null 2>&1
  fi
 let i++
 done
 # remove print-repo tmp file
 rm -f /tmp/print-repo-check-upgrade > /dev/null 2>&1
 rm -f /tmp/mem-check-upgrade > /dev/null 2>&1
}

fix_missing_files() {
  # this was primarily put in to fix bug 4980
  # upgrade of squid was failing if it's config file was missing
  if [ ! -f /etc/squid3/squid.conf ]
  then
    if [ -f /etc/squid3/squid.conf.bak ]
    then
      cp /etc/squid3/squid.conf.bak /etc/squid3/squid.conf
    else
      mkdir -p /etc/squid3
      touch /etc/squid3/squid.conf
    fi
    result=`echo $?`
    if [ "$result" != "0" ]; then
      echo 'failed to create missing squid3 config file'
      exit 1
    fi
  fi
}

check_repo() {

# if no repos configured in sources.list then fail out
num_repos=`cat /etc/apt/sources.list | awk {'print $1'} | grep "^deb$" | wc -l`
if [ "$num_repos" == "0" ]; then
 echo No repository configured to retrieve packages
 exit 1
fi

echo -e "$stars\nVyatta full-upgrade status - Configuring unpacked packages"
dpkg --configure -a || exit $?

echo -e "$stars\nVyatta full-upgrade status - Resynchronizing package index files"
# if unable to run apt-get update succesfully, report error
apt-get update >/tmp/$$-sim-apt-update 2>&1
result=`echo $?`
count_failed=`grep -i 'FAILED' /tmp/$$-sim-apt-update | wc -l`
if [ "$result" != "0" -o "$count_failed" != "0" ]; then
  echo -e "\nUnable to resynchronize package index files from their sources"
  echo "This may be due to one of the following reasons :"
  echo " * unable to resolve repository hostname"
  echo " * unable to connect to repository"
  echo " * repository not configured correctly"
  rm -f /tmp/$$-sim-apt-update
  exit 1
fi
rm -f /tmp/$$-sim-apt-update
}

full_upgrade_experimental_msg() {
echo -e "$stars\nPackage-based 'full-upgrade' process is no longer supported as of Vyatta version 6.3\n"
echo -e "Image-based upgrade process is now the only official upgrade path for"
echo -e "physical systems.  Please refer to the 'Image-based Upgrade' chapter"
echo -e "in the 'Install and Upgrade' section of the Vyatta documentation for"
echo -e "upgrade instructions."
echo -e "\nVirtualized Vyatta systems must follow the upgrade path described in the"
echo -e "'Upgrading in a Virtual Environment' chapter in the 'Install and Upgrade'"
echo -e "section of the Vyatta documentation."
echo -e "\n'full-upgrade' command is retained only for experimental purposes.  It may"
echo -e "render your system inoperable and should not be run on any production system."

response=''
while [ -z "$response" ]
  do
    echo -ne "\nAre you sure you want to proceed with the deprecated 'full-upgrade' process? (Y/N) [N]:"
    response=$(get_response "N" "Y N")
    if [ "$response" == "n" ]; then
      exit 1
   fi
done

if [ "$response" == "y" ]; then
  response=''
  while [ -z "$response" ]
    do
      echo -ne "\nThis may render your system inoperable!  Are you sure?  (Y/N) [N]:"
      response=$(get_response "N" "Y N")
      if [ "$response" == "n" ]; then
        exit 1
      fi
  done
fi
}


trap stop_parent_fullupgrade INT TERM EXIT

if [ `whoami` != 'root' ] ; then
    echo "full-upgrade must be run with root privileges."
    exit 1
fi

check_repo
cd /tmp
prevent_start_on_install
fix_missing_files
check-upgrade $* || exit
full_upgrade_experimental_msg

OPTION="$1"
[ "$OPTION" ] || OPTION=`ps l|grep -v grep|grep 'full-upgrade -'|sed 's,.*full-upgrade ,,'`
case "$OPTION" in
 -i )
	download-only "$OPTION" || exit $?
	/opt/vyatta/bin/_full-upgrade $OPTION
	;;

 -k )
	echo ===full-upgrade "$OPTION"===
	uptime
	date
	download-only "$OPTION" || exit $?
	if ! mkdir full-upgrade.lock
	then
		echo "full-upgrade can't acquire it's lock file (/tmp/full-upgrade.lock )."
		echo "You may be attempting to run full-upgrade more than once simultaneously."
		echo "If you want to proceed, then first rm -rf /tmp/full-upgrade.lock ."
		exit 1
	fi
	echo "Please wait.  Now entering unattended mode."
	echo "This will take a long time.  When done,"
	echo "the system will automatically reboot."
	hupfile=/root/nohup$$.out
	mkdir bak-$$
	mv /root/full-upgrade* bak-$$/.
	>/root/full-upgrade.log
	tail -f /root/full-upgrade.log&
	nohup /opt/vyatta/bin/_full-upgrade $OPTION>&$hupfile
	sleep 10
	cat /root/nohup$$.out
	rm -rf /tmp/full-upgrade.lock
	;;

 * )
	usage
	exit 1
esac
