#!/bin/bash

#=================================================
# GENERIC STARTING
#=================================================
# IMPORT GENERIC HELPERS
#=================================================

source _common.sh
source /usr/share/yunohost/helpers

#=================================================
# MANAGE SCRIPT FAILURE
#=================================================

# Exit if an error occurs during the execution of the script
ynh_abort_if_errors

#=================================================
# SPECIFIC GETTERS FOR TOML SHORT KEY
#=================================================

get__no_antenna() {
    if [[ "$(unused_iw_devices)" == "" ]]
    then
        echo "value: true"
    else
        echo "value: false"
    fi
}

get__status() {
    local service_enabled=$(ynh_app_setting_get $app service_enabled)
    if systemctl is-active hostapd@$app -q
    then
        if [[ "$service_enabled" -eq 1 ]]
        then
            cat << EOF
style: success
ask:
  en: |-
    Your Hotspot is running :)
EOF
        else
            cat << EOF
style: warning
ask:
  en: Your Hotspot is running, but it shouldn't !
EOF
        fi
    elif [[ "$service_enabled" -eq 1 ]]
    then
        cat << EOF
style: danger
ask:
  en: |-
    Your Hotspot is down ! Here are errors logged in the last 5 minutes
    \`\`\`
$(journalctl -u hostapd@$app -n10 -o cat | sed 's/^/    /g')
    \`\`\`
EOF
    else
        cat << EOF
style: info
ask:
  en: Your Hotspot is down as expected.
EOF

    fi
}

get__wifi_device() {
    local unused_wifi_devices=$(unused_iw_devices)
    if [[ -z "${unused_wifi_devices}" ]]
    then
        echo "choices: []"
    else
        cat << EOF
choices:
EOF
        for device in $unused_wifi_devices
        do
            echo "  $device: $device"
        done
    fi

    echo "value: '$(ynh_app_setting_get $app wifi_device)'"
}

get__dns() {
    ip6_net=$(ynh_app_setting_get --app=$app --key=ip6_net)
    ip6_dns=$(ynh_app_setting_get --app=$app --key=ip6_dns | tr -d '[]')
    ip4_nat_prefix=$(ynh_app_setting_get --app=$app --key=ip4_nat_prefix)
    ip4_dns=$(ynh_app_setting_get --app=$app --key=ip4_dns)

    if [[ -n "${ip6_net}" ]] && [[ -z "${ip6_dns}" ]]; then
        ip6_dns="${ip6_net}1"
    fi

    if [[ -n "${ip4_nat_prefix}" ]] && [[ -z "${ip4_dns}" ]]; then
        ip4_dns="${ip4_nat_prefix}.1"
    fi

    echo "value: ${ip4_dns},${ip6_dns}"
}

#=================================================
# SPECIFIC VALIDATORS FOR TOML SHORT KEYS
#=================================================

validate__wifi_ssid() {
    if [[ -z "${wifi_ssid}" ]]
    then
        echo 'SSID required'
    fi
}

validate__wifi_passphrase() {
    if [[ "${wifi_secure}" == "1" ]] && [[ -z "${wifi_passphrase}" ]]
    then
        echo 'In WPA2 secure mode, you need to provide a passphrase'
    fi
}

validate__ip4_nat_prefix() {
    if [[ -z "${ip4_nat_prefix}" ]]
    then
        echo 'Private IPv4 nat prefix required'
    fi
}

validate__dns() {
    if [[ -z "$ip4_dns" ]]
    then
        echo 'IPv4 DNS required'
    fi
    if [[ -n "${ip6_net}" ]] && [[ -z "$ip6_dns" ]]
    then
        echo 'IPv6 DNS required'
    fi
}

ynh_app_config_validate() {
    if [[ "${advanced}" -eq 0 ]]; then
        # When we aren't in advanced mode, these variables must be manually declared
        dns="${old[dns]}"
        ip6_net="${old[ip6_net]}"
        ip4_nat_prefix="${old[ip4_nat_prefix]}"
    fi

    ip6_dns=""
    ip4_dns=""
    for ip in $(echo "${dns}" | tr ',' ' '); do
        if [[ "$ip" == *":"* ]]; then
            ip6_dns+="[$ip],"
        else
            ip4_dns+="$ip,"
        fi
    done
    # Remove trailing ,
    ip6_dns="${ip6_dns%%,}"
    ip4_dns="${ip4_dns%%,}"

    if [[ -n "${ip6_net}" ]] && [[ -z "${ip6_dns}" ]]; then
        ip6_dns="${ip6_net}1"
    fi

    if [[ -n "${ip4_nat_prefix}" ]] && [[ -z "${ip4_dns}" ]]; then
        ip4_dns="${ip4_nat_prefix}.1"
    fi

    _ynh_app_config_validate
}

#=================================================
# SPECIFIC SETTERS FOR TOML SHORT KEYS
#=================================================

set__dns() {
    ynh_app_setting_set $app ip6_dns "${ip6_dns}"
    ynh_app_setting_set $app ip4_dns "${ip4_dns}"
}

#=================================================
# OVERWRITING VALIDATE STEP 
#=================================================

#=================================================
# OVERWRITING APPLY STEP 
#=================================================
ynh_app_config_apply() {
    service_name=$(ynh_app_setting_get --app=$app --key=service_name)

    # Stop vpn client
    ynh_print_info --message="Stopping hotspot in order to edit files"
    yunohost service stop $service_name

    _ynh_app_config_apply
    
    # Activate captive portal or not
    captive_portal=$(ynh_app_setting_get --app=$app --key=captive_portal)
    captive_portal_url=$(ynh_app_setting_get --app=$app --key=captive_portal_url)
    domain=$(cut -d'/' -f 3 <<< "${captive_portal_url}")
    if [[ "${captive_portal}" -eq 1 ]]; then
        ynh_add_nginx_config
	    ynh_systemd_action --service_name=captiveportal_fakedns --action="start" --log_path=systemd
    else
        ynh_remove_nginx_config
	    ynh_systemd_action --service_name=captiveportal_fakedns --action="stop" --log_path=systemd
    fi

    # Start vpn client
    ynh_print_info --message="Starting hotspot service if needed"
    /usr/local/bin/ynh-hotspot start

    if [[ "${service_enabled}" -eq 1 ]]; then
        configure_hostapd
        configure_dhcp

        # Start hotspot
        ynh_print_info --message="Starting hotspot service if needed"
        yunohost service start $service_name
    else
        ynh_print_info --message="Cleanup hotspot config files"
        ynh_secure_remove --file="/etc/hostapd/$app/hostapd.conf"
        ynh_secure_remove --file="/etc/dnsmasq.$app/dhcpdv4.conf"
        ynh_secure_remove --file="/etc/dnsmasq.$app/dhcpdv6.conf"

        systemctl restart dnsmasq
    fi

    yunohost tools regen-conf dnsmasq
}

ynh_app_config_run $1