#!/usr/bin/env bash
#
################################################################################
# BOARD SCRIPT, NOT FOR STANDALONE USE
################################################################################
#
# kyoungmeyer@emacinc.com
# December 9, 2013
#
# Copyright (C) 2013, EMAC, Inc.
# All rights reserved.      

Version="1.0"
version () { 
	echo "$(basename $0) (EMAC OE Automation Tools) Version $Version"
	echo "Copyright (C) 2013-2014 EMAC, Inc.  All rights reserved."; 
}
help () {
    echo
    echo "This is a board script that depends on another script to work"
    echo "properly, please do not use as a standalone script"
    echo
    echo "Options:"
    echo "  -v      Display version info and exit"
    echo "  -h      Display this help and exit"
    echo
    version
    echo
    echo "Copyright (C) 2013, EMAC, Inc."
    echo "All rights reserved."
    exit 0
}

INFO=/tmp/GDB_INFO
if [[ ! -f $INFO ]]; then
    echo "Transferred file not found"
    exit 1
fi
source "$INFO"
PROG_COM=${PROG_TARGET%% *}

if [[ ! -f "$PROG_COM" ]];then
    if [[ -f "/tmp/$PROG_COM" ]]; then
        PROG_TARGET="/tmp/$PROG_TARGET"
        PROG_COM="/tmp/$PROG_COM"
    else
        echo "Error: file: $PROG_COM does not exist"
        exit 1;
    fi
fi
if [[ ! -x "$PROG_COM" ]];then
    chmod u+x "$PROG_COM"
fi

# Credit to Mike Dean <mdean@emacinc.com> for daemonize code
################################################################################
#DAEMONIZE CODE
################################################################################
Program_Name="gdbserver $TARGET_MACH:$PORT $PROG_TARGET"
# Redirect tty file descriptors to /dev/null
redirect_fds()
{
	if [ -t 0 ]
	then
		exec < /dev/null
	fi

	if [ -t 1 ]
	then
		exec > /dev/null
	fi

	if [ -t 2 ]
	then
		exec 2> /dev/null
	fi
}
# Closes any non-standard file descriptors
close_open_fds()
{
	eval exec {3..255}\>\&-
}
# Launch as a daemon
daemonize()
{
	(
	redirect_fds
	cd /
	umask 0
	close_open_fds
	exec setsid "${Program_Name}"
	) &
}
################################################################################
#/DAEMONIZE CODE
################################################################################
while getopts ":vh" opt; do
  case $opt in
    v   ) version; exit 0;;
    h   ) help; exit 0;;
    \?  ) echo "Invalid option: -$OPTARG" >&2; exit 1;;
  esac
done


logger -t AUTOTOOLS "Launching $Program_Name as a daemon process."
daemonize

rm -f $INFO
