#!/bin/sh

# the following is not needed since the script is not
# anymore in the init procedure, will be called by the cryptroot script.
# PREREQ="dropbear"
#
# prereqs()
# {
     # echo "${PREREQ}"
# }
#
# case $1 in
# prereqs)
     # prereqs
     # exit 0
     # ;;
# esac
#
#. /scripts/functions

##
# Remarks
##
# - Using timeouts to avoid hanging problems.
# - If refactoring of code occurs, handle one subsection at time to lower
#   the checks.

################################################################################
# Constants 
##
true_value=0
false_value=1
SERVER_PORT_INT="22" #internal port of bmsoft network
SERVER_PORT_EXT="2242" #external port.
SERVER_PORT="${SERVER_PORT_EXT}"
SERVER_ADDR_byIP="144.76.241.146"
SERVER_ADDR_byFQDN="keyserver.bmsoft.de"
SERVER_ADDR="${SERVER_ADDR_byFQDN}"
  # check the busybox hook to see the libraries needed
  # to have a proper name resolution service.
SERVER_USER="bmsoft-cryptobox-server"
TESTING=${false_value}
waiting_for_reboot_sec=3600

if test ${TESTING} -eq ${true_value} ; then
  echo "TESTING VALUES!!"
  SERVER_PORT_INT="22"
  SERVER_PORT_EXT="2242"
  SERVER_PORT="${SERVER_PORT_INT}"
  SERVER_ADDR_byIP="172.22.11.40"
  SERVER_ADDR_byFQDN="172.22.11.40"
  SERVER_ADDR="${SERVER_ADDR_byIP}"
  SERVER_USER="bmsoft-cryptobox-server"
  waiting_for_reboot_sec=30
fi

################################################################################
# Helper Functions
##

# Parameters:
# ${1}: number of seconds to sleep
print_sleep () {
  seconds_to_sleep=${1}
  if test ! -n "${seconds_to_sleep}" ; then
    # no paramater, default value
    seconds_to_sleep=5
  fi
  echo -n "waiting "
  for num in $( seq 1 ${seconds_to_sleep} ); do
    sleep 1
    echo -n "."
  done
  echo "resume"
}

################################################################################
# grabbing the information about encrypted partitions (if they exists)
# check also the file to "preapare the target / extract the cryptroot from an existing image"
# in the other folders.
mkdir -p /mnt
cryptroot_source_name="cryptroot_info_file"
cryptroot_found_bool=${false_value}

echo "sleep waiting for the dev config"
print_sleep 10

echo "Trying to find a possible export of the cryptroot file, if was made at the installation time"
for possibleOpenUuid in $( ls /dev/disk/by-uuid/ ); do
  #check every possible uuid
  echo "checking ${possibleOpenUuid}"
  /sbin/cryptsetup isLuks "/dev/disk/by-uuid/${possibleOpenUuid}"
  if test $? -ne ${true_value} ; then # it is not luks.
    unencrypted_source="/dev/disk/by-uuid/${possibleOpenUuid}"
    echo "unencrypted_source ${unencrypted_source}"
    fs_type=$( /sbin/blkid | grep "${possibleOpenUuid}" | grep -o -i "type=\".*\"" | cut -d "=" -f 2 | tr -d '"' )
    echo "fs_type ${fs_type}"
    mount -t "${fs_type}" "${unencrypted_source}" /mnt
    if test $? -eq ${true_value} ; then
      echo "unencrypted_source ${unencrypted_source} mounted with FS ${fs_type}"
      if test -r "/mnt/${cryptroot_source_name}" -a -s "/mnt/${cryptroot_source_name}" ; then
        # file exist, is readable and its size is greater than zero.
        cp "/mnt/${cryptroot_source_name}" /conf/conf.d/cryptroot
        cryptroot_found_bool=${true_value}
      else
        echo "file not found, trying with the next partition"
      fi
      umount /mnt
    fi
  fi
  
  if test ${cryptroot_found_bool} -eq ${true_value}; then
    break
  fi
done

################################################################################
# network checks and config
# - configuring the DNS assuming that the DHCP server has provided good information
echo "checking the connectivity using the server ip address"

server_ip_is_reachable=${false_value}
for iterations in $(seq 1 15) ; do
  ping -c 1 -W 1 "${SERVER_ADDR_byIP}"
  if test $? -eq ${true_value} ; then
    # connectivity ok.
    server_ip_is_reachable=${true_value}
    break
  fi
  echo "network doesn't work, wait"
  print_sleep 10
done

if test ${server_ip_is_reachable} -eq ${false_value} ; then
  # the hopes to succeed are low, so we can set a trigger to restart the machine after a while
  # (the user can still insert the password manually)
  echo ""
  echo "scheduling a restart in the case no one takes actions"
  sleep "${waiting_for_reboot_sec}" && /bin/reboot &
    # 1h of waiting then reboot.
  exit 1
fi

dhcp_config_file_path=$( timeout -t 2 find /run/ -name "net*.conf" | tail -n 1 )
if test -z ${dhcp_config_file_path} ; then
  SERVER_ADDR="${SERVER_ADDR_byIP}"
else
  dns_ip=$( timeout -t 2 cat ${dhcp_config_file_path} | grep IPV4DNS | head -n 1 | cut -d "=" -f 2 | tr -d "'" )
fi

if test -z ${dns_ip} ; then
  SERVER_ADDR="${SERVER_ADDR_byIP}"
fi

echo ""
echo "pinging dns server"
ping -c 2 ${dns_ip}
if test $? -eq ${false_value} ; then
  SERVER_ADDR="${SERVER_ADDR_byIP}"
else
  echo "nameserver ${dns_ip}" > /etc/resolv.conf
fi

echo ""
echo "pinging the hostname of the server"
ping -c 2 ${SERVER_ADDR} 
if test $? -eq ${false_value} ; then
  SERVER_ADDR="${SERVER_ADDR_byIP}"
fi
echo ""
echo "SERVER_ADDR ${SERVER_ADDR}"

################################################################################
# asking for the passphrase to the keyserver
mac_addresses=$( ifconfig -a | grep -o -i "hwaddr.*$" | cut -d " " -f 2 )
  # we get a list of mac addresses
  
# constructing the json string to send towards the remote server
# note that this defines the communication protocol!
json_string='{"version":"2014-08-07",'
  # to differentiate different versions of the protocol
json_string="${json_string}"'"hwaddresses":['
for mac_addr in ${mac_addresses}; do
  json_string="${json_string}"'"'"${mac_addr}"'",'
done
json_string=${json_string%,}
  #delete the last ","
json_string="${json_string}""]"
json_string="${json_string}""}"
 
message="${json_string}"
if test ${TESTING} -eq ${true_value}; then
  # message=$( ifconfig | grep -o -i "hwaddr.*$" )
    # first version protocol
  : #do nothing
fi
echo "${message}"
luks_passphrases=$( /sbin/ssh -o StrictHostKeyChecking=no -i /root/.ssh/id_rsa -p ${SERVER_PORT} ${SERVER_USER}@${SERVER_ADDR} "${message}" )
#echo "Unlock pwd: ${luks_passhphrase}"

################################################################################
# configuring unlocking script
# unlocking_script_path="/scripts/bmsoft/unlock_2014_08_07"
# chmod +x "${unlocking_script_path}"
#just send the script in backround else it will prevent cryptsetup to run.
# "${unlocking_script_path}" "${luks_passphrases}" &
luks_passhphrases_file="/root/luks_passhphrases"
echo -n "${luks_passphrases}" > "${luks_passhphrases_file}"


