#!/bin/bash

#Set file name using rtd number and timestamp
file=$2-$(date +%F-%H-%M)

#Set directory path
if [ $1 -lt 9 ]; then
   dir=$IOC_DATA/ioc-und1-uc0"$1"/rtd/
else
   dir=$IOC_DATA/ioc-und1-uc"$1"/rtd/
fi

#Check for existance of directory, otherwise create
if [ -d $dir ]; then
   message=$(echo "Data will be saved under" $dir$file)
else
   message=$(echo "Data will be saved under new directory" $dir " file " $file)
   mkdir $dir
fi

#Check that pv connects, if not, set flag to 0
cainfo USEG:UND1:"$1"50:"$2"RAW > $dir/temp
temp=$(grep disconnected $dir/temp)
temp1=$(echo $temp | awk -F: '{print $2}')
temp1="x"$(echo $temp1)
temp2="x<disconnected>"
if [ $temp1 = $temp2 ]; then
   flag=0
else
   flag=1
fi
rm $dir/temp

#Get data if pv is connected while get data pv is true
if [ $flag -eq 1 ]; then
   flag1=$(caget -t USEG:UND1:"$1"50:GET"$2"DATA.RVAL)
   if [ $flag1 -eq 1 ]; then
      echo $message
   else
      echo "Get data pv not set, no data taken."
   fi
   while [ $flag1 -eq 1 ]; do
      caget -a USEG:UND1:"$1"50:"$2"RAW >> $dir$file
      flag1=$(caget -t USEG:UND1:"$1"50:GET"$2"DATA.RVAL)
      sleep 1
   done
else
   echo "No data saved"
fi

