#!/bin/sh
# define username and password
# define token and refresh token
USER="maxwellxzy@gmail.com"
PASSWD="sSZSTSWz.xhik8P"
USER_PASSWD="{
    \"username\": \"maxwellxzy@gmail.com\",
    \"password\": \"sSZSTSWz.xhik8P\"
}"

JSON_TOKEN=$(
    curl 'https://vps.hosting/api/login' \
    -d username=$USER\
    -d password=$PASSWD)

token=`echo $JSON_TOKEN|jq -r '.token'`
refresh_token=`echo $JSON_TOKEN|jq -r '.refresh'`
curl 'https://vps.hosting/api/login'  -d username=$USER  -d password=$PASSWD
##Set dir
SCRIPT_DIR=$(dirname "$0")
cd "$SCRIPT_DIR"

##########
# Function 
# to get token
# 1.read config file; if no config file or no token, getting token;jump to 3; 
# 2. judging token is repired;
#       if  token is repired, get new token and new refresh token; 
#       if token is not repired, return old token;
# 3. update config file (new token and new refresh token);
# 4. return new token;
#
get_token(){
# Define the get_token function
  # Set the config file path
  CONFIG_FILE="config.txt"

  # Check if the config file exists and has a token value
  if [ -f "$CONFIG_FILE" ] && [ -n "$(grep token $CONFIG_FILE)" ]; then
    # Read the token value from the config file
    TOKEN=$(grep token $CONFIG_FILE | cut -d '=' -f 2)

    # Check if the token is expired
    if [ "$(date +%s)" -gt "$(grep expiry $CONFIG_FILE | cut -d '=' -f 2)" ]; then
      # Use the API to get a new token and refresh token
      API_RESPONSE=$(curl -X POST https://example.com/api/token)

      # Extract the new token and refresh token from the API response
      NEW_TOKEN=$(echo $API_RESPONSE | jq '.token')
      REFRESH_TOKEN=$(echo $API_RESPONSE | jq '.refresh_token')

      # Write the new token and refresh token to the config file
      echo "token=$NEW_TOKEN" > $CONFIG_FILE
      echo "refresh_token=$REFRESH_TOKEN" >> $CONFIG_FILE

      # Return the new token
      echo $NEW_TOKEN
    else
      # Return the existing token
      echo $TOKEN
    fi
  else
    # Use the API to get a new token and refresh token
    API_RESPONSE=$(curl -X POST https://example.com/api/token)

    # Extract the new token and refresh token from the API response
    NEW_TOKEN=$(echo $API_RESPONSE | jq '.token')
    REFRESH_TOKEN=$(echo $API_RESPONSE | jq '.refresh_token')

    # Write the new token and refresh token to the config file
    echo "token=$NEW_TOKEN" > $CONFIG_FILE
    echo "refresh_token=$REFRESH_TOKEN" >> $CONFIG_FILE

    # Return the new token
    echo $NEW_TOKEN
  fi
}

    tmp_token=`curl -s -X POST "https://vps.hosting/api/login" \
   -H "Content-Type: application/json" \
   -d "$1"`

}

##########
# Function 
# to refresh token
# 1.read config file; if no config file or no refresh token, use function get_token; 
# 2. use refresh token to get new token;
#       if refresh token is repired, use function get_token; exit;
# 3. update config file;
#
get_refresh_token(){

}
## get services
