#! /bin/zsh

zmodload zsh/zutil


usage()
{
  cat << EOF
  Usage:
        $0 [ --token <token> (vs2FYr4VdYZhTx-Wg2Xt gitlab or XrjajV_pL_1tugzjdjs2 forgemia) ] [ --projectid <projectid> (23431674 gitlab or 3236 forgemia) ] --file <file_name> --version <version> --repos <forgemia | gitlab>
        Note how --token <token> and --projectid <projectid> are optional if the tokens file is available for these values to be searched for using the --repos <forgemia | gitlab> compulsory parameter.
EOF
}

if [ $1 = "--help" ] || [ $1 = "-h" ]
then
  usage
exit 0
fi

zparseopts -A opts -token: -file: -projectid: -version: -repos:

#echo "token: $opts[--token], file: $opts[--file], projectid: $opts[--projectid], version: $opts[--version], repos: $opts[--repos]"

packageradix=mineXpert2

repos="$opts[--repos]"

if [ -z "${repos}" ]
then
  print "Please provide a --repos \"<value>\", typically gitlab or forgemia\n"
  usage
  exit 1
fi

if [ ${repos} != "gitlab" ] && [ ${repos} != "forgemia" ] 
then
  print "Please provide a --repos \"<value>\", typically gitlab or forgemia\n"
  usage
  exit 1
fi

printf "Repos: ${repos}\n"


# Extract the token from the tokens file using a grep|sed command combination
reposurl=""
reposurl=$(grep "^rw-reposurl ${repos}" ~/devel/minexpert2/tokens/tokens | sed "s/rw-reposurl ${repos}: //")

if [ -z "${reposurl}" ]
then
  print "Please, fill in properly the tokens file, could not retrieve the repos url for repos ${repos}."
  usage
  exit 1
fi

printf "The repos url is: ${reposurl}\n"


# Extract the token from the tokens file using a grep|sed command combination
token=""
token=$(grep "^rw-token ${repos}" ~/devel/minexpert2/tokens/tokens | sed "s/rw-token ${repos}: //")

if [ ! -z "$opts[--token]" ]
then
  token=$opts[--token]
fi

projectid=""

# Extract the projectid from the tokens file using a grep|sed command combination
projectid=$(grep "^rw-projectid ${repos}" ~/devel/minexpert2/tokens/tokens | sed "s/rw-projectid ${repos}: //")

if [ ! -z "$opts[--projectid]" ]
then
  projectid="$opts[--projectid]"
fi


file="$opts[--file]"
filebasename=$(basename ${file})

if [ -z "${file}" ]
then
  print "Please provide a --file \"<file_name>\" to upload, typically minexpert2_7.2.0.orig.tar.gz \n"
  usage
  exit 1
fi


version="$opts[--version]"

if [ -z "${version}" ]
then
  print "Please provide a --version \"<value>\", typically 7.4.0.\n"
  usage
  exit 1
fi


printf "\nCommand to run: curl --verbose --header \"PRIVATE-TOKEN: ${token}\" --upload-file ${file} \"${reposurl}/${projectid}/packages/generic/${packageradix}/${version}/${filebasename}\"\n"

curl --verbose --header "PRIVATE-TOKEN: ${token}" --upload-file ${file} "${reposurl}/${projectid}/packages/generic/${packageradix}/${version}/${filebasename}"

printf "\nCommand that was run: curl --verbose --header \"PRIVATE-TOKEN: ${token}\" --upload-file ${file} \"${reposurl}/${projectid}/packages/generic/${packageradix}/${version}/${filebasename}\"\n"

