#!/usr/bin/perl
# relink_gcc unlinks the old gcc and links the current version
#
# SYNOPSIS:
# cd /usr/local/bin
# relink_gcc
#
# DESCRIPTION:
# Homebrew installs gcc version N.X as gcc-N. All other components
# of the Gnu Compiler Collection are installed with the '-N' suffix.
# E.g. g++-N, c++-N, ... However, I prefer to have the names w/o
# the '-N' suffix so I can use the same Makefiles on different
# computers. This program changes the links from the plain gcc
# (and its family) to point to the most recent gcc version.
# Because 'darwin' also changes version, the program changes the
# version of programs with 'darwin' in their names to the current
# version. The gcc and darwin versions are currently hardcoded.
#
# CAVEAT:
# Make a backup of /usr/local/bin and /usr/local/Cellar before
# using this script
use strict;
use warnings;
# Set parameters here. I might add command line args at some point.
#..Dry run only prints what would be done. Does not actually do it.
my $dryrun = 1;
my $new_version = 10;
my $ending = "-$new_version";
my $re_ending = qr/$ending/;
# ..In case upgrading one sub-version to another (e.g. 5.2.0 to 5.3.1)
# (moot if upgrading to new version (e.g. 5.N.M to 6.K.L)
my $old_sub = qr/5\.2\.0/;
my $new_sub = qr/$new_version\.2\.0/;
# ..To find the Darwin version, at the command line prompt enter
# uname -r
my $new_darwin_version = "17.7.0";
# No changes needed below this line (I hope)
my @gcc_N_list = glob qq("*${ending}");
print "found $#gcc_N_list files ending in '$ending'\n";
# ..If the file exists but is not a link, leave it alone.
if (-e $plain && (! -l $plain )){
print "$plain is not a link\n";
next;
}
# ..File pointed to by '$file'
my $orig = readlink($file);
if ($dryrun) {print "$file -> $orig\n";}
# __Change versions to current ones if sub-version upgrade
# ..Gnu compiler collection version
$orig =~ s/${old_sub}/${new_sub}/g;
# ..Apple Darwin version
$orig =~ s/(darwin)\d{2}\.\d\.\d/$1$new_darwin_version/;
# ..Skip non-existent files
if (! -e $orig){
print "\t$orig does not exist. Skip!\n";
next;
}
# ..Remove existing files before linking
if (-e $plain || -l $plain ){
print "$plain exists\n";
if ($dryrun) {
print "\tWould remove $plain\n";
print "\tunlink $plain\n";
}
else {
unlink $plain or die "Unable to unlink $plain $!\n";
}
}
else {
print "\t$plain does not exist would create\n";
}
# ..Finally! link the new version
if ($dryrun) {
print "\twould symlink $orig, $plain;\n";
}
else {
symlink $orig, $plain
or die "Unable to symlink $orig to $plain:$!\n";
}
}