#!/bin/sh
VERSION=1.0-r25
user=pod
PODCTL_F=/etc/podctl.conf

cmd=$1
shift

net_add() {
    custom_iface=""
    [ "$1" = "-i" ] && { custom_iface=$2; shift 2; }
    name=$1
    ip=$2
    shift 2
    [ -z "$name" ] && { echo "Error: pod name required"; exit 1; }
    [ -z "$ip" ] && { echo "Error: IP address required"; exit 1; }
    case "$name" in
        [0-9]*.[0-9]*.[0-9]*.[0-9]*) echo "Error: name cannot be an IP address"; exit 1 ;;
    esac
    case "$ip" in
        *[!0-9.]*|"") echo "Error: invalid IP '$ip'"; exit 1 ;;
    esac
    IFS=. read -r _o1 _o2 _o3 _o4 << EOF
$ip
EOF
    for _o in "$_o1" "$_o2" "$_o3" "$_o4"; do
        { [ -z "$_o" ] || [ "$_o" -gt 255 ] 2>/dev/null; } && { echo "Error: invalid IP '$ip'"; exit 1; }
    done
    for _arg in "$@"; do
        case "$_arg" in
            *-*) _s=${_arg%-*}; _e=${_arg#*-}
                 case "$_s$_e" in *[!0-9]*) echo "Error: invalid port '$_arg'"; exit 1 ;; esac ;;
            *) case "$_arg" in *[!0-9]*) echo "Error: invalid port '$_arg'"; exit 1 ;; esac ;;
        esac
    done
    iface=$(ip -4 route show default|awk '{print $5}')
    [ -n "$custom_iface" ] && iface=$custom_iface
    gw=$(ip -4 route show dev "$iface"|awk '/^default/{print $3}')
    [ -z "$gw" ] && gw=$(ip -4 route show default|awk '{print $3}')
    nm=$(ip -4 addr show "$iface"|grep "inet "|head -n1|awk '{print $2}'|cut -d/ -f2)
    ports_meta="$*"
    ports=$(for arg in "$@"; do
        case "$arg" in
            *-*)
                start=${arg%-*}; end=${arg#*-}; port=$start
                while [ "$port" -le "$end" ]; do printf ",-t,%s/%s" "$ip" "$port"; port=$((port + 1)); done
                ;;
            *)
                printf ",-t,%s/%s" "$ip" "$arg"
                ;;
        esac
    done)

    touch "$PODCTL_F"
    echo "$name:$ip:$iface:$nm:$ports_meta" >> "$PODCTL_F"
    ip addr add "$ip/$nm" dev "$iface" label "$iface:$name" 2>/dev/null || true
    su - "$user" -s /bin/sh -c "podman pod create --name $name --infra-name pod_$name --network \"pasta:--address,$ip,--gateway,$gw,--netmask,$nm,--map-gw$ports\""
}

net_del() {
    name=$1
    line=$(grep "^$name:" "$PODCTL_F" 2>/dev/null)
    pip=$(echo "$line"|cut -d: -f2)
    piface=$(echo "$line"|cut -d: -f3)
    pnm=$(echo "$line"|cut -d: -f4)
    su - "$user" -s /bin/sh -c "podman pod rm -f $name"
    ip addr del "$pip/$pnm" dev "$piface" 2>/dev/null || true
    sed -i "/^$name:/d" "$PODCTL_F"
    [ -s "$PODCTL_F" ] || rm -f "$PODCTL_F"
}

net_start() {
    [ -f "$PODCTL_F" ] || return 0
    while IFS=: read -r pname pip piface pnm _; do
        case "$pname" in "#"*|"") continue ;; esac
        ip addr add "$pip/$pnm" dev "$piface" label "$piface:$pname" 2>/dev/null || true
    done < "$PODCTL_F"
}

net_stop() {
    [ -f "$PODCTL_F" ] || return 0
    while IFS=: read -r pname pip piface pnm _; do
        case "$pname" in "#"*|"") continue ;; esac
        ip addr del "$pip/$pnm" dev "$piface" 2>/dev/null || true
    done < "$PODCTL_F"
}

list_pods() {
    filter=$1
    first=1
    [ -f "$PODCTL_F" ] || { printf '[]\n'; return 0; }
    printf '[\n'
    while IFS=: read -r pname pip piface pnm pports; do
        case "$pname" in "#"*|"") continue ;; esac
        [ -n "$filter" ] && [ "$pname" != "$filter" ] && continue
        status=$(su - "$user" -s /bin/sh -c "podman pod inspect $pname --format '{{.State}}'" 2>/dev/null || echo "unknown")
        ports_json=$(echo "$pports"|awk '{
            n=split($0,a," "); printf "[";
            for(i=1;i<=n;i++) printf (i==1)? "\""a[i]"\"" : ",\""a[i]"\"";
            printf "]"
        }')
        [ "$first" = "1" ] && first=0 || printf ',\n'
        printf '  {\n'
        printf '    "name": "%s",\n' "$pname"
        printf '    "ip": "%s",\n' "$pip"
        printf '    "ports": %s,\n' "$ports_json"
        printf '    "status": "%s"\n' "$status"
        printf '  }'
    done < "$PODCTL_F"
    printf '\n]\n'
}

migrate() {
    iface=$(ip -4 route show default|awk '{print $5}')
    nm=$(ip -4 addr show "$iface"|awk '/inet / && !/secondary/ {print $2}'|cut -d/ -f2)
    remaining=$(ip -4 addr show "$iface"|awk '/inet / && /secondary/ {print $2}'|cut -d/ -f1|tr '\n' ' ')
    pods=$(su - "$user" -s /bin/sh -c "podman pod ls --format json"|grep '"Name":'|grep -v '"Names":'|awk -F'"' '{print $4}')

    : > "$PODCTL_F"

    for pod in $pods; do
        printf 'Pod: %s\n' "$pod"
        printf 'IPs: %s\n' "$remaining"
        printf 'IP (skip=enter): '
        read -r sel
        [ -z "$sel" ] && continue
        printf 'Ports (e.g. 80 443 8080-8090, skip=enter): '
        read -r ports
        echo "$pod:$sel:$iface:$nm:$ports" >> "$PODCTL_F"
        ip addr del "$sel/$nm" dev "$iface" 2>/dev/null || true
        ip addr add "$sel/$nm" dev "$iface" label "$iface:$pod"
        remaining=$(printf '%s' "$remaining"|tr ' ' '\n'|grep -v "^$sel$"|tr '\n' ' ')
    done

    remaining=$(printf '%s' "$remaining"|tr -s ' '|sed 's/^ //;s/ $//')
    [ -n "$remaining" ] && {
        printf 'Remaining IPs: %s\n' "$remaining"
        printf 'Remove from eth0? [y/N]: '
        read -r answer
        case "$answer" in
            y|Y)
                for rip in $remaining; do
                    ip addr del "$rip/$nm" dev "$iface" 2>/dev/null || true
                done
                ;;
        esac
    }

    [ -d /run/systemd/system ] && { systemctl enable podctl || true; } || rc-update add podctl default
    printf 'Migration complete.\n'
}

case "$cmd" in
    net)
        subcmd=$1; shift
        case "$subcmd" in
            add)   net_add "$@" ;;
            del)   net_del "$@" ;;
            start) net_start ;;
            stop)  net_stop ;;
            *) echo "Uso: $0 net add|del|start|stop [args...]"; exit 1 ;;
        esac
        ;;
    list)
        list_pods "$1"
        ;;
    enable)
        root=""; [ "$1" = "--root" ] && { root=1; shift; }
        name=$1
        [ ! -e /pods ] && { printf 'Path for /pods: '; read -r pods_path; ln -s "$pods_path" /pods; }
        [ -n "$root" ] && {
            [ -d /run/systemd/system ] && systemctl enable pod@"$name" || ln -s /etc/rc.service/init.d/pod /etc/init.d/"$name"
        } || {
            [ -d /run/systemd/system ] && systemctl enable rootless-pod@"$name" || ln -s /etc/rc.service/init.d/rootless-pod /etc/init.d/"$name"
        }
        ;;
    disable)
        root=""; [ "$1" = "--root" ] && { root=1; shift; }
        name=$1
        [ -n "$root" ] && {
            [ -d /run/systemd/system ] && systemctl disable pod@"$name" || rm -f /etc/init.d/"$name"
        } || {
            [ -d /run/systemd/system ] && systemctl disable rootless-pod@"$name" || rm -f /etc/init.d/"$name"
        }
        ;;
    edit)
        root=""; [ "$1" = "--root" ] && { root=1; shift; }
        name=$1
        [ ! -e /pods ] && { printf 'Path for /pods: '; read -r pods_path; ln -s "$pods_path" /pods; }
        [ -n "$root" ] && {
            [ -d /run/systemd/system ] && {
                cp /usr/lib/systemd/system/pod@.service /etc/systemd/system/pod@"$name".service
                ${EDITOR:-nano} /etc/systemd/system/pod@"$name".service
                systemctl daemon-reload
            } || {
                cp /etc/rc.service/init.d/pod /etc/rc.service/init.d/"$name"
                ${EDITOR:-nano} /etc/rc.service/init.d/"$name"
                ln -sf /etc/rc.service/init.d/"$name" /etc/init.d/"$name"
            }
        } || {
            [ -d /run/systemd/system ] && {
                cp /usr/lib/systemd/system/rootless-pod@.service /etc/systemd/system/rootless-pod@"$name".service
                ${EDITOR:-nano} /etc/systemd/system/rootless-pod@"$name".service
                systemctl daemon-reload
            } || {
                cp /etc/rc.service/init.d/rootless-pod /etc/rc.service/init.d/"$name"
                ${EDITOR:-nano} /etc/rc.service/init.d/"$name"
                ln -sf /etc/rc.service/init.d/"$name" /etc/init.d/"$name"
            }
        }
        ;;
    migrate)
        migrate
        ;;
    version)
        echo "$VERSION"
        ;;
    "")
        echo "Uso: $0 net add|del|start|stop|list [nome]|enable|disable|edit <nome>|migrate|version|<comando podman>"
        exit 1
        ;;
    *)
        su - "$user" -s /bin/sh -c "podman $cmd $*"
        ;;
esac
