Howto use apt-cacher-ng only when available?

Solution 1:

From the server you can announce to the network there is an apt-cacher-ng instance through avahi

From the client you can check if exist an apt-cacher-ng service and modify apt proxy settings accordly.


Server

Install

$ sudo apt-get install apt-cacher-ng squid-deb-proxy-client

For Ubuntu releases older than 14.04 put the following snippet in /etc/avahi/services/apt-cacher-ng.service:

<?xml version="1.0" standalone='no'?>
<!DOCTYPE service-group SYSTEM "avahi-service.dtd">
<service-group>
 <name replace-wildcards="yes">apt-cacher-ng proxy on %h</name>
 <service protocol="ipv4">
  <type>_apt_proxy._tcp</type>
  <port>3142</port>
 </service>
</service-group>

Client

Install

$ sudo apt-get install squid-deb-proxy-client

Here is a snippet to install server|client depending if there is already an apt-get proxy or not:

  • https://gist.github.com/chilicuil/6207489

Source: http://blog.surgut.co.uk/2013/03/avahi-apt-cacher-ng-sbuild.html

Solution 2:

Something like this should work:

/etc/NetworkManager/dispatcher.d

#!/bin/bash
ip=10.0.1.13
port=3142
nc -w 1 $ip $port
proxy_file="/etc/apt/apt.conf.d/02local_proxy"
if [ $? -eq 0 ]; then
    echo "Acquire::http { Proxy \"http://$ip:$port\"; };" > $proxy_file
    echo 'Acquire::https { Proxy "false"; };' >> $proxy_file
else
    rm -f $proxy_file
fi

Fix permissions

sudo chmod +x /etc/NetworkManager/dispatcher.d/99SetAptProxy

Notes:

  • The "nc" command tests that it can connect to the 3142 port on the given IP address.
  • This script is run everytime the networking interfaces are changed by network manager.
  • Feel free to alter the way that you detect for the proxy, this works for me, but it is a security vulnerability if you install packages on a foreign network, for example.