package Ifweb::Iwconfig;

use strict;
use warnings;

use Dancer ':syntax';

sub init {
    my $if = shift;
    system('rfkill unblock wifi');
    system("ifconfig $if up");
}

sub keyval {
    my $keyval = shift;
    my ($key, $value) = split(/\s*:|=\s*/, $keyval, 2);

    $key   =~ s/^\s+//;
    $key   =~ s/\s+g$//;
    $value =~ s/^\s+//;
    $value =~ s/\s+g$//;

    return ($key, $value);
}

sub scan {
    my $iface = shift;

    init $iface;

    open(my $iwconfig, "iwlist $iface scan |");

    my @cells = ();
    my $cell = {};
    my $tmp = {};
    my $id = -1;

    if (<$iwconfig> =~ /No scan results/) {
        return \@cells;
    }

    while (<$iwconfig>) {
        chomp;

        if (/^\s*Cell/ || /^\s*$/) {
            if ($id >= 0) {
                $cell->{iface} = $iface;

                $cell->{address} = $tmp->{Address};
                $cell->{mode}    = $tmp->{Mode};

                $tmp->{ESSID} =~ s/"//g;
                $cell->{ESSID} = $tmp->{ESSID};

                $tmp->{Quality} =~ s/ .*//g;
                $cell->{quality} = $tmp->{Quality};

                $cell->{encryption} = "Off";
                if ($tmp->{"Encryption key"} eq "on") {
                    $cell->{encryption} = "WEP";

                    if (exists $tmp->{IE} && $tmp->{IE} =~ /WPA/) {
                        my $auth;
                        if ($tmp->{"Authentication Suites (1)"} =~ /PSK/) {
                            $cell->{encryption} = "WPA-PSK";
                        }
                        else {
                            $cell->{encryption} = "WPA";
                        }
                    }
                }
                $cell->{id} = $id;

                push @cells, $cell;
            }

            if (! /^\s*$/) {
                s/Cell.*-\s+//;
                my ($key, $value) = keyval $_;
                $tmp = {$key => $value};
                $cell = {};
                $id++;
            }

            next;
        }

        if (/:|=/) {
            my ($key, $value) = keyval $_;
            if (exists $tmp->{$key}) {
                $tmp->{$key} .= "\n";
                $tmp->{$key} .= $value;
            }
            else {
                $tmp->{$key} = $value;
            }
        }
    }

    close($iwconfig);

    session cells => \@cells;
    return \@cells;
}

true;
