#!/bin/sh

#
# Copyright (C) 2022 Nethesis S.r.l.
# SPDX-License-Identifier: GPL-2.0-only
#

# Unregister dedalo unit
# Usage example: 
#     unregister_dedalo <reseller_user> <reseller_password>
#     unregister_dedalo <token_file>

username=$1
password=${2:-""}

token_file="/var/run/dedalo_token"
api_url=$(uci get dedalo.config.api_url)

if [ -z "$username" ]; then
    exit 2
fi

if [ -z "$password" ]; then
    # read the token from a file
    if [ -f "$token_file" ]; then
        token=$(cat $token_file)
    else
        exit 3
    fi
else
    # execute login
    token=$(curl -s --request POST --url "$api_url/login" --header 'Content-Type: ap/loginplication/json' --data-binary '{"username": "'$username'", "password": "'$password'"}' | jq -r .token)
fi

# retrieve internal unit ID
uuid=$(/sbin/uci get dedalo.config.unit_uuid)
unit_id=$(curl -X GET --url "$api_url/units?q=$uuid" --header "Token: $token" --header "Content-Type: application/json" -s | jq -r ".data | .[0].id")

# Delete the unit from remote server
curl -X DELETE --url "$api_url/units/$unit_id" --header "Token: $token" --header "Content-Type: application/json" -s

# cleanup local config
/sbin/uci set dedalo.config.disabled=1
/sbin/uci delete dedalo.config.hotspot_id
/sbin/uci delete dedalo.config.interface
/sbin/uci delete dedalo.config.unit_name
/sbin/uci delete dedalo.config.unit_description
/sbin/uci delete dedalo.config.secret
/sbin/uci delete dedalo.config.unit_uuid
/sbin/uci commit dedalo

# Disable dedalo services
/etc/init.d/dedalo stop
/etc/init.d/dedalo_users_auth stop

# Cleanup token
if [ -f "$username" ]; then
    rm -f "$username"
fi
