#!/usr/bin/env bash

. /usr/share/dosis2/bin/shell-support-functions

serial="$1"
siteserverip="`/opt/dosis2/etc/personality/common-scripts/siteserver-ip-from-config`"

pill_environments="`psql -Aqt -U dpg -d dosis2 \
    -c \"select dct.tag as camera_type, dlt.tag as lighting_type \
        from equipment.dafe_pill_environment dpe \
        inner join equipment.dafe_camera_types dct on dct.id = dpe.camera_type_id \
        inner join equipment.dafe_lighting_types dlt on dlt.id = dpe.lighting_type_id \
        order by dct.tag, dlt.tag\"`"

declare -a pillenvs
for pe in ${pill_environments}; do
    pillenvs+=(${pe})
done


echo "Choose Camera and Lighting Kit"
echo "--------------------------"
printf "    %10s |%10s\n" "Camera" "Lighting"
echo "--------------------------"
count=0
for pe in ${pillenvs[@]}; do
    camera="`echo \"${pe}\" | cut -d\| -f1`"
    lighting="`echo \"${pe}\" | cut -d\| -f2`"
    printf "[${count}] %10s |%10s\n" "${camera}" "${lighting}"
    let count=count+1
done


while [ true ]; do
    index="`/opt/dosis2/etc/personality/common-scripts/ask \
        \"Choose Pill Environment: \" \
        \"^[0-9]+$\"`"

    [ $? = 0 ] && [ ${index} -ge 0 ] && [ ${index} -le ${count} ] && break

    echo -e "\033[31mChoose among [0-${count}]\033[0m"
done


pillenv="${pillenvs[${index}]}"
camera="`echo \"${pillenv}\" | cut -d\| -f1`"
lighting="`echo \"${pillenv}\" | cut -d\| -f2`"
apply_pill_env="""
update equipment.dafe
set pill_environment_id = (
    select dpe.id from equipment.dafe_pill_environment dpe
        inner join equipment.dafe_camera_types dct on dct.id = dpe.camera_type_id
        inner join equipment.dafe_lighting_types dlt on dlt.id = dpe.lighting_type_id
    where dct.tag = '${camera}'
        and dlt.tag = '${lighting}')
where dafe_sn = '${serial}'
"""
if [ "${siteserverip}" = "" ]; then
    psql -U dpg -d dosis2 -c "${apply_pill_env}"
else
    psql -U dpg -d dosis2 -h "${siteserverip}" -c "${apply_pill_env}"
fi
