#!/bin/bash -l


###################################################
##
##    This is a script for Setup/switch Experiment
##
##   
##
####################################################

source armory/Process_BasicConfig

############### Check is git exist
isGitExist=0
if [ -d $(pwd)/".git" ]; then
  echo -e "Git repository exists."
else
  echo -e "Git repository does not exist. Abort."
  if [ ${PCID} -eq 1 ]; then
    echo -e "Use SOLARIS DAQ to setup new experiment"
  fi
  exit
fi

if [ ${PCID} -eq 1 ]; then
  echo -e "================================================ ${YELLOW}SOLARIS DAQ ${NC}"
elif [ ${PCID} -eq 2 ]; then
  echo -e "================================================ ${YELLOW}SOLARIS MAC ${NC}"
else
  echo -e "================================================ ${YELLOW}Other PC ${NC}"
fi
echo " The bach script do following things "
echo " 1) git-fetch  "
echo " 2) check repository is clean"
echo " 3) check is git branch exist"
echo "    branch exist --> git checkout "
echo "    branch not exist --> create expName.sh"
echo " 4) making directories for data, root_data"
echo " 5) create symbolic links to data, root_data"
echo " 6) Tell Database SetupNewExp change exp. (only from the DAQ)"
echo " 7) git push (if new exp.)"
echo "============================================================="

expName=$1

###############  this will define global enviroment varibales, like the analysis path, export armory
source SOLARIS.sh

###############  Check git
echo -e "${YELLOW} 1) ################## Git Fetch ${NC}"
echo "when password is needed, please edit .git/config"
git fetch

echo -e "${YELLOW} 2) ################## Checking git repository is clean or not.... ${NC}"
gitCheck=`git status --porcelain --untracked-files=no | wc -l`
if [ ${gitCheck} -eq 0 ]; then
  echo "---- clean."
else
  git status
  echo -e "\033[0;93m=============== Please fix the git status \033[0m"
  exit
fi

if [ $# -eq 0 ]; then
  git branch -a
  read -p 'Enter the new experiment name: ' expName    
fi

############### check is there any GIt branch in repository, 
#               if not create Git Branch, if yes, checkout
echo -e "${YELLOW} 3) ################## Checking/Create Git Branch ${NC}"
pullFlag="K"
isBranchExist=`git branch -a | grep ${expName} | wc -l`
if [ ${expName} == "Master" ]; then
  echo "this is the Master experiment name. no branch create. checkout Master"
  git checkout Master
  isBranchExist=1
else

  if [ ${isBranchExist} -eq 0 ]; then

    if [ ${PCID} -eq 1 ]; then

      echo -e "You are going to create a${GREEN} NEW ${NC}branch ${CYAN}${expName}${NC} from branch : $(git branch --show-current)"
      read -p "Are you sure? (Y/N) " createNewBranch
      if [ ${createNewBranch} == "Y" ]; then
        git checkout -b ${expName}
      else
        exit
      fi
    
    else

      echo -e "${CYAN} ONLY the DAQ machines can create branch ${NC}"

    fi

  else
    echo -e "Experimental (branch) Name ${expName} ${GEEN} already exist ${NC}."
    echo "Please take another name or git pull origin ${expName}"
    read -p "Do you want to checkout origin/${expName} (Y/N):"  pullFlag
    if [ ${pullFlag} == "N" ]; then
      exit
    else
      git checkout ${expName}
    fi
  fi
fi

############### set up expName.sh, so that all experimental Name is refered to this name
if [ ${isBranchExist} -eq 0 ]; then

  workingDir=$(pwd)"/working/"
  expNamePath=$(pwd)"/working/expName.sh"
  echo -e "${YELLOW} 3a) ################## Setting up ${expNamePath} ${NC}"

  if [ ! -d ${workingDir} ]; then
      mkdir -p ${workingDir}  # create parent directory
  fi

  touch ${expNamePath}
  echo "#!/bin/bash -l" > ${expNamePath}
  echo "expName=${expName}" >> ${expNamePath}
  echo "rawDataPath=${rawDataPathParent}"/${expName} >> ${expNamePath}
  echo "rootDataPath=${rootDataPathParent}"/${expName} >> ${expNamePath}
  echo "runID=0" >> ${expNamePath}
  echo "elogID=0" >> ${expNamePath}
  echo "#------------end of file." >> ${expNamePath}
fi

echo -e "${YELLOW} 4) ##################  making new folders in ${rawDataPathParent} ${NC}"

if [ ${PCID} -eq 1 ]; then
  rawData=${rawDataPathParent}/${expName}
  rootData=${rootDataPathParent}/${expName}
elif [ ${PCID} -eq 2 ]; then
  rawData=${rawDataPathParent}/${expName}/data
  rootData=${rootDataPathParent}/${expName}/root_data
else

  path=$(pwd)
  read -p "Please enter absolute DATAPATH (e.g. ${path}) " DATAPATH
  echo "DATAPATH for    raw data : ${DATAPATH}/${expName}/data"
  echo "DATAPATH for   root_data : ${DATAPATH}/${expName}/root_data"   

  rawData=${DATAPATH}/${expName}/data
  rootData=${DATAPATH}/${expName}/root_data

fi

mkdir -v ${rawData}
mkdir -v ${rootData}

############### create symbolic links
echo -e "${YELLOW} 5) ################## creating symbolic links ${NC}"
rm -f data_raw
rm -f root_data

ln -sfv ${rawData} data_raw
ln -sfv ${rootData} root_data


if [ ${PCID} -eq 1 ]; then 

  ############### tell Database SetupNewExp change exp.
  
  echo -e "=================== Tell the database"

  haha1=${databaseIP}"/write?db="${databaseName}

  if [ ${isBranchExist} -eq 0 ]; then
    haha2="RunID,start=0 value=0,expName=\"${expName}\",comment=\"New_experiment_[${expName}]_was_created.\""
  else

    source working/expName.sh

    haha2="RunID,start=0 value=${runID},expName=\"${expName}\",comment=\"Experiment_[${expName}]_was_switched.\""
  fi
  #echo $haha1
  #echo $haha2
  curl -s -v -XPOST "$haha1" --data-binary "$haha2"  --max-time 1 --connect-timeout 1

  #===== clean up working if it is new
  if [ ${isBranchExist} -eq 0 ]; then

    echo "======== Clean up working directory "
    #rm -fv working/correction_*.dat
    rm -fv working/reaction.dat
    rm -fv working/run_Summary.dat
    rm -fv working/example.*
    rm -fv working/RunTimeStamp.dat
    rm -fv working/*.root
    rm -fv working/*.d
    rm -fv working/*.so
    rm -fv working/*.pcm

    echo "======== git commit "
    git add -A
    git commit -m "New experiment ${expName}"

    echo -e "${YELLOW} 5) ################## git push ${NC}"
    git push origin ${expName}

  fi 

fi



