#!/bin/bash

program_name=ocs
git_root_dir=$(dirname $(dirname $(dirname $(realpath $0))))
build_root_dir=${git_root_dir}/build
rel_dir_205=/mnt/public/documents/Project_sum-up/2G-Baicell-Zambia/22.04/ocs
debs_rel_dir_205=${rel_dir_205}
server_ip_205=192.168.1.205
user_205=agtuser
passwd_205=admin123

usage() {
	echo "Usage: sh cpto205.sh ocs|scp|ussdgw [rel_date]"
    echo "  ocs|scp|ussdgw      specify program name"
	echo "  [rel_date]          should be in the format YYYYMMDD, current date if not specified"
}

if [ ! -z "$1" ]; then
	program_name=$1
else 
    usage 
fi

rel_dir_local=${build_root_dir}/release/${program_name}
rel_arch=amd64

if [ ! -z "$2" ]; then
	rel_date=$2
else
	rel_date=$(date +%Y%m%d)
fi

release_note_file=${rel_dir_local}/${program_name}_release_note.txt
latest_deb_file=$(ls -t ${rel_dir_local}/${rel_arch}/*${rel_date}* 2>/dev/null | head -n 1)

# Use expect to automatically answer yes and input password for rsync commands

if [ -n "${latest_deb_file}" ]; then
    expect <<EOF
    set timeout -1
    spawn rsync -avz ${latest_deb_file} ${user_205}@${server_ip_205}:${debs_rel_dir_205}
    expect {
        "yes/no" { 
            send "yes\n"
            exp_continue 
        }
        "password:" { send "${passwd_205}\n" }
    }
    expect eof
EOF
fi

if [ -f "${release_note_file}" ]; then
    expect <<EOF
    set timeout -1
    spawn rsync -avz ${release_note_file} ${user_205}@${server_ip_205}:${debs_rel_dir_205}
    expect {
        "yes/no" { 
            send "yes\n"
            exp_continue 
        }
        "password:" { send "${passwd_205}\n" }
    }
    expect eof
EOF
fi

